Why does this hex value get output as a negative number?
char buffer_b[5] = { 0xDA, 0x00, 开发者_JAVA技巧0x04, 0x00, 0x07 };
printf("%d\n%d\n%d", buffer_b[0], buffer_b[2], buffer_b[4]);
This gives me output:
-38
4
7
However I am expecting:
218
4
7
Thanks.
char is signed. Use unsigned char.
use %ud also.
Evidently, char
is signed in your environment. (That's a detail that can vary from one implementation to the next, and some compilers even offer you an option through a command-line switch.) The number you're printing is 0xDA, which has the most significant bit set, so its value is negative. When the compiler passes that value to printf
, it promotes the (signed) char value to type int
, and it retains its negativity. You used the %d
format string, which tells printf
to interpret its argument as a signed value.
To treat the value as unsigned, you should at a minimum use the %u
format string. Then either change your array's element type to be an unsigned type, such as unsigned char
or uint8_t
, or type-cast the printf
argument to unsigned
.
When the char
0xDA
is promoted to int
to pass to printf
, the compiler is doing a sign-extension, converting it to 0xffffffda
, which is the 32-bit representation of -38
. You were expecting it to be zero-extended to 0x000000da
. To control how the compiler extends a character, you have declare it as signed char
or unsigned char
. Signed integer types are widened by sign-extending, and unsigned integer types are widened by zero-extending.
You can't predict how any particular compiler will treat an unqualified char
, or if it will be the same in the next release of the compiler.
精彩评论