我正在尝试strtol
将包含ASCII HEX值的uint8_t
数组的部分转换为整数值。这意味着在串行端口上接收的字节以ASCII值格式化为“89ABC”等。
但是strtol
会将收到的uint8_t
数组的其余部分从起始位置转换为完全错误的值。所以我必须这样做:
tempvalue = MerdPC.buf[15]; MerdPC.tiltcmd=(uint8_t)strtol(&tempvalue, NULL, 16);
tempvalue = MerdPC.buf[16]; MerdPC.tiltparam=((uint16_t)strtol(&tempvalue, NULL, 16))<<8;
tempvalue = MerdPC.buf[17]; MerdPC.tiltparam|=((uint16_t)strtol(&tempvalue, NULL, 16))<<4;
tempvalue = MerdPC.buf[18]; MerdPC.tiltparam|=(uint16_t)strtol(&tempvalue, NULL, 16);
这很有效。但有没有更好的方法,不涉及临时变量?
编辑:
输入字符串示例为:
十六进制值:23 31 43 30 30 30 30 30 30 30 30 30 30 30 31 37 38 39 0D 0A
ASCII:#1C000000000000 1789 ..
四个粗体字符分别是tiltcmd byte和tiltparam bytes。
答案 0 :(得分:1)
这有帮助吗?
char tiltparam[] = "#1C0000000000001789..";
char temp[5] = { 0 };
strncpy(temp, &tiltparam[15], 4);
int tempvalue = strtol(temp, NULL, 10);
...
我们仍然需要temp
缓冲区,但它比您的解决方案更短,更易读。
或者如果你在其他地方有更多像这样的转换,你可以创建一个函数:
int ExtractHex(const char *hexstr, int offset)
{
char temp[5] = { 0 };
strncpy(temp, &hexstr[offset], 4);
return strtol(temp, NULL, 10);
}
...
int somevalue = ExtractHex(tiltparam, 15);
...