C/C++ Printing bytes in hex, getting weird hex values

前端 未结 2 1060
感动是毒
感动是毒 2021-01-16 01:42

I am using the following to print out numbers from an array in hex:

char buff[1000];

// Populate array....

int i;
for(i = 0; i < 1000; ++i)
{
    printf         


        
2条回答
  •  臣服心动
    2021-01-16 01:59

    Your platform apparantly has signed char. On platforms where char is unsigned the output would be f4.

    When calling a variadic function any integer argument smaller than int gets promoted to int.

    A char value of f4 (-12 as a signed char) has the sign bit set, so when converted to int becomes fffffff4 (still -12 but now as a signed int) in your case.

    %x02 causes printf to treat the argument as an unsigned int and will print it using at least 2 hexadecimal digits. The output doesn't fit in 2 digits, so as many as are required are used.

    Hence the output fffffff4.

    To fix it, either declare your array unsigned char buff[1000]; or cast the argument:

        printf("[%d] %02x\n", i, (unsigned char)buff[i]);
    

提交回复
热议问题