I am converting a string representation of a mac address into an array of UINT8
s defined as unsigned char
. I am curious why sscanf()
will read all 0s when I read into an array of UINT8
s and actual values when I read into an array of regular 32 bit int
s. Its almost like it's chopping off the 8 bits of the wrong end of the int.
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
Update: %hhx
will work for C99 and above, but I have an old codebase so I ended up going with strtoul()
:
char *str = strMac;
int i = 0;
for(i = 0; i < 6; i++, str+=3) {
uMAC[i] = strtoul(str, NULL, 16);
}