0

I'm trying to save an integer as a character.

char i = 80;
printf("0x%x", i);

The above code displays 0x50 (1 byte). But if the value is above 128, it prints a 4 byte value.

char i = 130;
printf("0x%x", i); // this prints 0xffffff82

How can I store the integer value as just 1 byte if the value is greater than 128 (print just 82 instead of ffffff82 in second example) ?

jww
  • 97,681
  • 90
  • 411
  • 885
hmdb
  • 323
  • 1
  • 4
  • 11
  • 3
    use `unsigned char i = 130;` – Marian Apr 05 '14 at 18:17
  • The `%x` format specifier will print a hexadeimal value. I believe `i` is being promoted, so you are printing an integer, not a 8-bit octet. That's why you are seeing the `0xffffff82`. You will also have to worry about `int` -> `char` truncations (in the general case). – jww Apr 05 '14 at 18:20

1 Answers1

1

This is the expected behavior on systems where char type is signed: negative values of char get sign-expanded to the size of an int.

If you would like to print the last eight bits, you could mask with 0xFF, like this:

printf("0x%x", i & 0xFF); // this prints 80

Demo on ideone.

An alternative approach is to use unsigned char. This would avoid sign extension for 8-bit numbers with the most significant bit set to 1.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523