Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing the hex value stored as a string gives unexpected output

I have in C language hex numbers defined in string:

char chars[] = "\xfb\x54\x9c\xb2\x10\xef\x89\x51\x2f\x0b\xea\xbb\x1d\xaf\xad\xf8";

Then I want to compare the values with another. It is not working and if I print the value like:

printf("%02x\n", chars[0]);

it writes fffffffb. Why is that and how to get fb value exactly?

like image 235
H.W. Avatar asked Aug 06 '15 10:08

H.W.


1 Answers

This is because of the sign extension.

Change

printf("%02x\n", chars[0]);

to

printf("%02x\n", (unsigned char)chars[0]);

The %x format specifier will read 4 bytes on 32bit machine. As you have declared chars as the character array, when fetching the value fb(negative value) will be sign extended as fffffffb, where the MSB of fb is set to all other bits before it.

Refer this for more details sign extension

If you would have declared char chars[] as unsigned char chars[] then the print would have been as expected.

like image 122
Santosh A Avatar answered Sep 19 '22 10:09

Santosh A