1

In the following code I stored the mac address in a char array.

But even when I am storing it in a char variable, while printing it's printing as follows:

ffffffbb

ffffffcc

ffffffdd

ffffffee

ffffffff

This is the code:

#include<stdio.h>
int main()
{
        char *mac = "aa:bb:cc:dd:ee:ff";
        char a[6];int i;
        sscanf(mac,"%x:%x:%x:%x:%x:%x",&a[0],&a[1],&a[2],&a[3],&a[4],&a[5]);
        for( i = 0; i < 6;i++)
        printf("%x\n",a[i]);
}

I need the output to be in the following way:

aa

bb

cc

dd

ee

ff

The current printf statement is

printf("%x\n",a[i]);

How can I get the desired output and why is the printf statement printing ffffffaa even though I stored the aa in a char array?

Lundin
  • 195,001
  • 40
  • 254
  • 396
Siva Kannan
  • 2,237
  • 4
  • 27
  • 39

2 Answers2

4

You're using %x, which expects the argument to be unsigned int *, but you're just passing char *. This is dangerous, since sscanf() will do an int-sized write, possibly writing outside the space allocated to your variable.

Change the conversion specifier for the sscanf() to %hhx, which means unsigned char. Then change the print to match. Also, of course, make the a array unsigned char.

Also check to make sure sscanf() succeded:

unsigned char a[6];
if(sscanf(mac, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
          a, a + 1, a + 2, a + 3, a + 4, a + 5) == 6)
{
   printf("daddy MAC is %02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx",
          a[0], a[1], a[2], a[3], a[4], a[5]);
}
unwind
  • 391,730
  • 64
  • 469
  • 606
3

Make sure to treat your a array as unsigned chars, i.e.

unsigned char a[6];

In

printf("%x\n",a[i]);

the expression a[i] yields a char. However, the standard does not specify whether char is signed or unsigned. In your case, the compiler apparently treats it as a signed type.

Since the most significant bit is set in all the bytes of your Mac address (each by is larger than or equal to 0x80), a[i] is treated as a negative value so printf generates the hexadecimal representation of a negative value.

Community
  • 1
  • 1
Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207
  • hm.. can you explain why that makes a difference? – WeaselFox Feb 11 '14 at 09:42
  • @WeaselFox I just extended my answer a bit, does that help? – Frerich Raabe Feb 11 '14 at 09:46
  • I *really* think this should address the `sscanf()` issue, too. – unwind Feb 11 '14 at 10:02
  • @unwind I feel your answer addresses the issues with the `sscanf` calls quite nicely, I don't think I have anything to add to that. The incorrect usage of `sscanf` is not the reason for why the expected and observed output given by the OP diverges though (you'd have the same issue if `a` was initialized like `char a[] = { 0xaa, 0xbb, 0xcc ... };`). So my answer focused on that. – Frerich Raabe Feb 11 '14 at 10:06