3

I am absolutly not doing C, but for a small thing, I need to make a very simple function. I have problem understanding the result.

I have a MAC address and I need to output the PIN code. (wiimote) I got this function so far

int main(int argc, char *argv[])
{
char pin[6];
pin[0] = 0x61;
pin[1] = 0xC7;
pin[2] = 0x5E;
pin[3] = 0x00;
pin[4] = 0x9E;
pin[5] = 0xCC;
printf(pin);
return 0;
}

Problem is that I get as a result: aヌ^ Is it what I am supposed to get? Value should be different?

The point as David Hoelzer said, I might find a solution converting Hexa to string?

Thank you!

orugari
  • 414
  • 3
  • 17
  • Regardless of @mohan's answer, you will still only see three characters. These are hexadecimal values, only two of which look to be typical printable ASCII. The fourth one (`pin[3]`) is a null, which will terminate your string. This data is not intended to be printed as a string. – David Hoelzer Jan 13 '16 at 05:40
  • A MAC is a 6 byte address, not a printable string. – David Hoelzer Jan 13 '16 at 05:40
  • I see, so I need to convert this hexadecimal value to a string? which will display something normal? – orugari Jan 13 '16 at 05:42
  • `Is it what I am supposed to get?` well, it is your program so you should know what you expect. When you know what you want, you can get help. – Support Ukraine Jan 13 '16 at 05:50
  • You are right, but since I am not understanding C, I don't know what printf should return. I know what I want (a PIN code), but not what I am doing. – orugari Jan 13 '16 at 05:52
  • How do the PIN code look? Show example of expected output. – Support Ukraine Jan 13 '16 at 05:56
  • http://stackoverflow.com/questions/8060170/printing-hexadecimal-characters-in-c – Punit Vara Jan 13 '16 at 07:12

1 Answers1

3

Is this what you need?

unsigned char pin[6];   // Unsigned ...
pin[0] = 0x61;
pin[1] = 0xC7;
pin[2] = 0x5E;
pin[3] = 0x00;
pin[4] = 0x9E;
pin[5] = 0xCC;

printf("%02x:%02x:%02x:%02x:%02x:%02x\n",pin[0],pin[1],pin[2],pin[3],pin[4],pin[5]);

will print

61:c7:5e:00:9e:cc

Explanation:

%x   // Print a number in hexadecimal format using lower case (%X for upper case)
%2x  // Print at least 2 characters (prepend with space)
%02x // Print at least 2 characters and prepend with 0

Use unsigned char pin[6] to avoid sign extention during print. If you use char pin[6] you'll get

61:ffffffc7:5e:00:ffffff9e:ffffffcc

which is probably not what you want.

If you for some reason need to use char, you can do:

char pin[6];
pin[0] = 0x61;
pin[1] = 0xC7;
pin[2] = 0x5E;
pin[3] = 0x00;
pin[4] = 0x9E;
pin[5] = 0xCC;

printf("%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx\n",pin[0],pin[1],pin[2],pin[3],pin[4],pin[5]);
           ^^
           Force type to char
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63