c - 如何设置 strtol 的限制
c - How to set limits for strtol
我正在尝试 strtol
将包含 ASCII HEX 值的 uint8_t
数组的一部分转换为整数值。这意味着串行端口上接收到的字节格式为“89ABC”等 ASCII 值。
但是 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 30 31 37 38 39 0D 0A
ASCII:#1C0000000000001789..
四个加粗字符分别为tiltcmd字节和tiltparam字节
这有帮助吗?
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);
...
我正在尝试 strtol
将包含 ASCII HEX 值的 uint8_t
数组的一部分转换为整数值。这意味着串行端口上接收到的字节格式为“89ABC”等 ASCII 值。
但是 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 30 31 37 38 39 0D 0A
ASCII:#1C0000000000001789..
四个加粗字符分别为tiltcmd字节和tiltparam字节
这有帮助吗?
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);
...