C – Printf Char as Hexadecimal

c++printf

I expect ouput something like \9b\d9\c0... from code below, but I'm getting \ffffff9b\ffffffd9\ffffffc0\ffffff9d\53\ffffffa9\fffffff4\49\ffffffb0\ffff
ffef\ffffffd9\ffffffaa\61\fffffff7\54\fffffffb
. I added explicit casting to char, but it has no effect. What's going on here?

typdef struct PT {
    // ... omitted
    char GUID[16];
} PT;
PT *pt;
// ... omitted
int i;
for(i=0;i<16;i++) {
    printf("\\%02x", (char) pt->GUID[i]);
}

Edit: only casting to (unsigned char) worked for me. Compiler spits warnings on me when using %02hhx (gcc -Wall). (unsigned int) had no effect.

Best Answer

The reason why this is happening is that chars on your system are signed. When you pass them to functions with variable number of arguments, such as printf (outside of fixed-argument portion of the signature) chars get converted to int, and they get sign-extended in the process.

To fix this, cast the value to unsigned char:

printf("\\%02hhx", (unsigned char) pt->GUID[i]);

Demo.

Related Question