我有一个字符数组(像aa:bb:cc:dd:ee:ff
这样的以太网地址),我需要解析成unsigned char[6]
。我使用strtok来获取每个字符对,并且我需要将它们转换为一个无符号字符,但是我所做的一切都没有发挥作用。将char *长度2转换为无符号字符的正确方法?
我尝试(假设c
是长度为2的一个char *):
unsigned char t = (unsigned char)c; // gives "loses precision" error
unsigned char* t = (unsigned char*)c;
unsigned char t1 = t[0]; // gives the wrong value
unsigned char t;
strcpy((char*)t, c); // gives the wrong value
strncpy((char*)t, c, sizeof(char)*2) // gives the wrong value
“c”是如何定义的?你的'strncpy'代码也有错误。 – 2012-04-21 17:44:59
@macs固定。往上看。 – xdumaine 2012-04-21 17:46:05
你试过['strtoul(c,NULL,16)'](http://www.cplusplus.com/reference/clibrary/cstdlib/strtoul/)吗?它可能会给你“失去精度”的警告,但会产生一个无符号整数(第一个令牌的值为'0xAA'等)。 – DCoder 2012-04-21 17:47:27