-1

I have following C code.

char a[] = "\x7f\x80";
printf("0x%02x\n",a[0]);
printf("0x%02x",a[1]);

It should print,

0x7f
0x80

However I'm getting following ?

0x7f
0xffffff80

What changes I have to make to get the output 0x7f 0x80?

Thanks,

Dev.K.
  • 2,428
  • 5
  • 35
  • 49

1 Answers1

3

Use the correct types and conversion specifiers:

unsigned char a[] = "\x7f\x80";
printf("0x%02hhx\n",a[0]);
printf("0x%02hhx",a[1]);

Conversion specifier x requires an unsigned type, and the length modifier hh is used for unsigned char.

2501
  • 25,460
  • 4
  • 47
  • 87