【发布时间】:2015-10-27 04:38:03
【问题描述】:
我正在将 mac 地址的字符串表示形式转换为定义为 unsigned char 的 UINT8s 数组。我很好奇为什么当我读入UINT8s 的数组时sscanf() 会读取全0,而当我读入常规的32 位ints 的数组时会读取实际值。它几乎就像是在切掉 int 错误端的 8 位。
char *strMAC = "11:22:33:AA:BB:CC";
typedef unsigned char UINT8;
UINT8 uMAC[6];
int iMAC[6];
sscanf( (const char*) strMac,
"%x:%x:%x:%x:%x:%x",
&uMAC[0], &uMAC[1], &uMAC[2], &uMAC[3], &uMAC[4], &uMAC[5] );
printf( "%x:%x:%x:%x:%x:%x",
uMAC[0], uMAC[1], uMAC[2], uMAC[3], uMAC[4], uMAC[5] );
// output: 0:0:0:0:0:0
sscanf( (const char*) strMac,
"%x:%x:%x:%x:%x:%x",
&iMAC[0], &iMAC[1], &iMAC[2], &iMAC[3], &iMAC[4], &iMAC[5] );
printf( "%x:%x:%x:%x:%x:%x",
iMAC[0], iMAC[1], iMAC[2], iMAC[3], iMAC[4], iMAC[5] );
// output: 11:22:33:AA:BB:CC
更新:%hhx 适用于 C99 及更高版本,但我有一个旧代码库,所以我最终选择了 strtoul():
char *str = strMac;
int i = 0;
for(i = 0; i < 6; i++, str+=3) {
uMAC[i] = strtoul(str, NULL, 16);
}
【问题讨论】:
-
您在此处调用了未定义的行为,因此提供的任何解释都不完整。
-
char *strMac = "11:22:33:AA:BB:CC";? -
不是这里的主要问题,但在
sscanf( (const char*) strMac,...中不需要(const char*)。