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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With