STM32汉字字符串转换成16进制保存到数组
时间: 2023-10-24 09:05:21 浏览: 159
您可以使用以下方法将汉字字符串转换为16进制并保存到数组中:
```c
#include <stdio.h>
#include <string.h>
void stringToHex(const char* str, uint8_t* hexArray, size_t hexArraySize) {
size_t strLen = strlen(str);
size_t hexArrayLen = 0;
for (size_t i = 0; i < strLen; i++) {
if (hexArrayLen >= hexArraySize) {
break;
}
uint8_t high = (str[i] & 0xF0) >> 4;
uint8_t low = str[i] & 0x0F;
hexArray[hexArrayLen++] = high;
if (hexArrayLen >= hexArraySize) {
break;
}
hexArray[hexArrayLen++] = low;
}
}
int main() {
const char* chineseStr = "你好世界";
size_t chineseStrLen = strlen(chineseStr);
size_t hexArraySize = chineseStrLen * 2;
uint8_t hexArray[hexArraySize];
stringToHex(chineseStr, hexArray, hexArraySize);
printf("Hex array: ");
for (size_t i = 0; i < hexArraySize; i++) {
printf("%02X ", hexArray[i]);
}
printf("\n");
return 0;
}
```
这段代码将会把汉字字符串转换为对应的16进制值,并保存到数组 `hexArray` 中。每个汉字字符会被转换为两个16进制值,分别存储高位和低位。在上面的示例中,字符串 "你好世界" 被转换为 `hexArray` 数组:`E4 B8 89 E5 A5 BD E4 B8 96 E7 95 8C`。
阅读全文