what happens when %x read signed char?

159 Views Asked by At

enter image description here

i thought *(p3 + 3) will print 90 but it shows ffffff90 why does it happend? i guess MSB is 1, and %x is for reading unsinged hexadecimal integer so it reads 90 like minus integer but it is not clear and i cant find about this problem at printf reference https://cplusplus.com/reference/cstdio/printf/ is there anyone who explain this?

1

There are 1 best solutions below

2
ikegami On BEST ANSWER

Use an unsigned char *.


In your environment,

  • char is signed.
  • char is 8 bits.
  • Signed numbers use two's complement.

So you have a char with a bit pattern of 9016. In this environment, that's -112. So you are effectively doing the following:

printf( "%x", (char)-112 );

When passing to variadric function like printf, the smaller integer types are implicitly promoted to int or unsigned int. So what's really happening is this:

printf( "%x", (int)(char)-112 );

So you're passing the int value -112. On your machine, that has the bit pattern FF FF FF 9016 (in some unknown byte order). %x expects an unsigned integer, and thus prints that bit pattern as-is.