char mac[] = "00:13:a9:1f:b0:88";
int a[6];
sscanf(mac, "%x:%x:%x:%x:%x:%x", &a[0], &a[1], &a[2], &a[3], &a[4],
&a[5]);
generally, it worked. But when mac contains something like "0(x)" it breaks
for example
char mac[] = "01:13:a9:1f:b0:88"; // 01 became 00 in above code
any trick?
This due to memory issues which caused by other parts of the program
**Keeping here for inspiration **
sscanf knows to ignore leading zeros.
I've tried your code on windows with visual studio, and on linux with gcc and it works fine. I suggest you check again your results, as your program seems to work fine.
if you want your 'a' array be printed the same as the input use printf with %02x modifier
simple solution:
char mac[] = "00-13-a9-1f-b0-88";
int a[6];
sscanf(mac, "%x-%x-%x-%x-%x-%x", &a[0], &a[1], &a[2], &a[3], &a[4], &a[5]);
Then copy values of 'a' to char array.
Your code works fine. Check this
int main()
{
char mac1[] = "0x2:0x13:0xa9:0x1f:0xb0:0x88";
char mac2[] = "02:13:a9:1f:b0:88";
int a[6];
sscanf(mac1, "%x:%x:%x:%x:%x:%x", &a[0], &a[1], &a[2], &a[3], &a[4], &a[5]);
printf("%02x:%02x:%02x:%02x:%02x:%02x\n", a[0], a[1], a[2], a[3], a[4], a[5]);
sscanf(mac2, "%x:%x:%x:%x:%x:%x", &a[0], &a[1], &a[2], &a[3], &a[4], &a[5]);
printf("%02x:%02x:%02x:%02x:%02x:%02x\n", a[0], a[1], a[2], a[3], a[4], a[5]);
}
Output:
02:13:a9:1f:b0:88
02:13:a9:1f:b0:88
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.