先看看下面这段代码有什么问题吧:
int _tmain(int argc, _TCHAR* argv[])
{
unsigned char in_mac[2] = {0xd0, 0x01};
char *mac = (char *)in_mac;
char info[50] = {0};
sprintf_s(info, "%02x%02x", mac[0], mac[1]);
return 0;
}
info,在sprintf之后,值并不是期望的d001,而是ffffffd001。为什么?
mac[0]的值就是0xd0,也就是一个负数。在sprintf里面%02x实际上接受的值是32位的,也就是0xd0,需要放大到32位。放大的过程就是:
0xd0 == -48
-48 == ~48 +1 == 0xffffffd0
所以修改:
unsigned char *mac = (unsigned char *)in_mac;