[英]char* string to hex arrary in C
I have char * para.mac
, string c8934641d0b7
stored in it.我有 char *
para.mac
,字符串c8934641d0b7
存储在其中。
I want to convert it to hex array int m[6]
, make我想将它转换为十六进制数组
int m[6]
,使
m[0]=0xc8;
m[1]=0x93;
...
m[5]=0xb7;
I tried to do it with:我尝试这样做:
int i;
int m[6];
sscanf(para.mac, "%x%x%x%x%x%x", &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]);
for(i=0;i<6;i++)
printf("%i \r\n",m[i]);
but it seems doesn't working.但它似乎不起作用。
and I don't know why the result shows to me like:我不知道为什么结果显示给我:
1178718391
0
0
134448233
8
134272063
I think it should be我认为应该是
200(0xc8)
147(0x93)
70(0x46)
65(0x41)
208(0xd0)
183(0xb7)
so what's the problem?所以有什么问题?
You're on the right track, if I'm not mistaken.如果我没记错的话,你是在正确的轨道上。
Consider trying: "%2x%2x%2x%2x%2x%2x"
, which means that each hex digit will only consume at most 2 characters.考虑尝试:
"%2x%2x%2x%2x%2x%2x"
,这意味着每个十六进制数字最多只消耗 2 个字符。
You are using the only %x in the sscanf
function.您正在使用
sscanf
函数中唯一的 %x。
sscanf(buf, "%x%x%x%x%x%x", &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]);
Which will get only character of hexadecimal.这将只获得十六进制字符。 But it should take two characters to convert it.
但是转换它应该需要两个字符。 You can change the
sscanf
function like this:您可以像这样更改
sscanf
函数:
sscanf(buf, "%2x%2x%2x%2x%2x%2x", &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]);
Now as per your string : c8934641d0b7
The first %2x will get c8
and the second %2x will get 93
, the third will get 46
fourth will get 41
fifth will get d0
and finally fifth will get b7
.现在根据您的字符串:
c8934641d0b7
第一个 %2x 将获得c8
,第二个 %2x 将获得93
,第三个将获得46
第四个将获得41
第五个将获得d0
最后第五个将获得b7
。
So it will work fine now.所以它现在可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.