In a portion of my program, I'll have to manage signed 8-bit integers. I have no problem to display them as decimals using printf
and %d
formatting.
However, when it comes to hexadecimal representation, the formatting of a negative int8_t
variable is not shown as a 8-bit hexadecimal (0xXX
) but as a 32-bit hexadecimal (0xFFFFFFXX
).
Here is the snippet of code, describing my problem:
#include <stdio.h>
#include <stdint.h>
int main()
{
int8_t value = 0;
printf("t = %d = 0x%02X\n", value, value);
t = 127;
printf("t = %d = 0x%02X\n", value, value);
t = -128;
printf("t = %d = 0x%02X\n", value, value);
return 0;
}
Compilation and execution give:
t = 0 = 0x00
t = 127 = 0x7F
t = -128 = 0xFFFFFF80
I would like to get 0x80
and not 0xFFFFFF80
. What did I do wrong? How to display the negative signed 8-bit integer as a 8-bit hexadecimal?