4

I am coding a C code and I want to compare the hexadecimal value of some character with an other. That is working, but with somme value like I obtained a value on 4 bytes which create a no sense in my comparaison.

void obs_text(char* start, unsigned char debugLevel, unsigned char depth){
    printf("%c -> 0x%x\n", start[0], start[0]);
}

I expected an output with two hexadecimals characters but the actual output is ? -> 0xffffffef. Please does any one understand what happens ? Thank you for your help.

I am compiling with gcc.

Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/c++/4.2.1
Apple LLVM version 10.0.1 (clang-1001.0.46.3)
Target: x86_64-apple-darwin18.2.0
Thread model: posix

but I also try on a Debian OS with the same problem

LoStack
  • 43
  • 4

2 Answers2

3

Because %x means display as an unsigned integer (4 bytes) as hexadecimal. See http://www.cplusplus.com/reference/cstdio/printf/

As noted there, you could use %hhx (added in C99) to get the behavior you were expecting (see more in this answer).

John Cummings
  • 1,949
  • 3
  • 22
  • 38
1

Use %hhx and cast the argument to unsigned char:

printf( "%c - 0x%hhx", start[0], (unsigned char) start[0] );

%x expects its corresponding argument to have type unsigned int. You need to use the hh length modifier to tell it that you're dealing with an unsigned char value.

John Bode
  • 119,563
  • 19
  • 122
  • 198
  • Note: `(unsigned char)` not needed. Both `(unsigned char) start[0]` and `start[0]` are converted to an `int` before calling `printf()`. `printf()` takes that `int` and then cast to `unsinged char` as part of the `%hhx` specifier. – chux - Reinstate Monica Apr 12 '19 at 21:22