将十六进制字符串转换为数据
我已经找到了很多不同的解决方案来解决这个问题,但并不是所有的解决方案都有效,而且其中很多看起来都有些老套和低效。基本上我有一串十六进制数据(即“55 AA 41 2A 00 94 55 AA BB BB 00 FF”),我想将其转换为原始数据。最好的方法是什么?
更新:Vicky 的解决方案对我来说非常有用,但我将其更改为使用中间没有空格的十六进制字符串,并稍微更改了样式。
int i = 0;
char *hexString = "55AA412A009455AABBBB00FF"
char *hexPtr = hexString;
unsigned int *result = calloc(strlen(hexString)/2 + 1, sizeof *result);
while (sscanf(hexPtr, "%02x", &result[i++])) {
hexPtr += 2;
if (hexPtr >= hexString + strlen(hexString)) break;
}
return result;
I have found a whole lot of different solutions to this problem, but not all of them work, and a lot of them seem somewhat hacky and inefficient. Basically I have a string of hexadecimal data (i.e. "55 AA 41 2A 00 94 55 AA BB BB 00 FF") which I would like to convert to raw data. What is the best way to do this?
UPDATE: Vicky's solution worked great for me, but I changed it to work with hexadecimal strings that don't have spaces in between and changed the style a bit.
int i = 0;
char *hexString = "55AA412A009455AABBBB00FF"
char *hexPtr = hexString;
unsigned int *result = calloc(strlen(hexString)/2 + 1, sizeof *result);
while (sscanf(hexPtr, "%02x", &result[i++])) {
hexPtr += 2;
if (hexPtr >= hexString + strlen(hexString)) break;
}
return result;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您是否尝试过
sscanf
或scanf
?该函数处理十六进制值并返回“原始数据”。Did you try
sscanf
orscanf
? This function processes hexadecimal values to and returns "raw data".字符串的长度总是相同吗?
如果是:
如果不是:
Is the string always the same length?
If so:
If not: