[英]How to convert hex string to byte array in CAPL?
Considering having, for example, this type of hex string:例如,考虑到这种类型的十六进制字符串:
char hex_str[100] = "0x01 0x03 0x04 0x0A";
How to get out of this string the byte array representation in CAPL, like:如何从这个字符串中取出 CAPL 中的字节数组表示,例如:
byte hex_str_as_byte_arr[4] = {0x01, 0x03, 0x04, 0x0A};
EDIT: Only Vector CANoe supported data types/functions are allowed!编辑:只允许使用 Vector CANoe 支持的数据类型/函数!
使用strtok
将字符数组拆分为单独的十六进制字符串,然后使用long strtol( const char *restrict str, char **restrict str_end, int base )
将每个十六进制字符串转换为整数值。
Thanks to all... Actually I've found a solution myself:感谢所有人......实际上我自己找到了一个解决方案:
char hex_str[100] = "0x01 0x03 0x04 0x0A";
long data[4];
dword pos = 0;
pos = strtol(hex_str, pos, data[0]);
pos = strtol(hex_str, pos, data[1]);
pos = strtol(hex_str, pos, data[2]);
pos = strtol(hex_str, pos, data[3]);
write("0x%02x,0x%02x,0x%02x, 0x%02x", data[0], data[1], data[2], data[3]);
Now it's a simple cast: (byte) data[0]
现在是一个简单的转换: (byte) data[0]
We can use sscanf()
to convert the numbers to unsigned char
.我们可以使用sscanf()
将数字转换为unsigned char
。 In a loop, we'll need to also use a %n
conversion to determine the reading position for the next iteration.在循环中,我们还需要使用%n
转换来确定下一次迭代的读取位置。
Here's a simple example (in real life, you'll need some range checking to make sure you don't overrun the output buffer):这是一个简单的示例(在现实生活中,您需要进行一些范围检查以确保不会超出输出缓冲区):
#include <stdio.h>
int main(void)
{
const char hex_str[100] = "0x01, 0x03, 0x04, 0x0A";
unsigned char bytes[4];
{
int position;
unsigned char *b = bytes;
for (const char *input = hex_str; sscanf(input, "%hhi, %n", b, &position) == 1; ++b) {
input += position;
}
}
/* prove we did it */
for (size_t i = 0; i < sizeof bytes; ++i) {
printf("%hhu ", bytes[i]);
}
puts("");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.