[英]what happens when %x read signed char?
i thought *(p3 + 3) will print 90 but it shows ffffff90 why does it happend?我以为 *(p3 + 3) 会打印 90 但它显示 ffffff90 为什么会发生? i guess MSB is 1, and %x is for reading unsinged hexadecimal integer so it reads 90 like minus integer but it is not clear and i cant find about this problem at printf reference https://cplusplus.com/reference/cstdio/printf/ is there anyone who explain this?
我猜 MSB 是 1,而 %x 用于读取无符号十六进制整数,因此它读取 90 就像负整数一样,但不清楚,我在 printf 参考https://cplusplus.com/reference/cstdio/printf上找不到这个问题/有人解释一下吗?
Use an unsigned char *
.使用
unsigned char *
。
In your environment,在你的环境中,
char
is signed. char
已签名。char
is 8 bits. char
是 8 位。 So you have a char
with a bit pattern of 90 16 .所以你有一个位模式为 90 16的
char
。 In this environment, that's -112.在这种环境下,这是-112。 So you are effectively doing the following:
因此,您实际上是在执行以下操作:
printf( "%x", (char)-112 );
When passing to variadric function like printf
, the smaller integer types are implicitly promoted to int
or unsigned int
.当传递给像
printf
这样的可变参数函数时,较小的整数类型被隐式提升为int
或unsigned int
。 So what's really happening is this:所以真正发生的事情是这样的:
printf( "%x", (int)(char)-112 );
So you're passing the int
value -112.所以你传递的是
int
值 -112。 On your machine, that has the bit pattern FF FF FF 90 16 (in some unknown byte order).在您的机器上,它的位模式为 FF FF FF 90 16 (以某种未知的字节顺序)。
%x
expects an unsigned integer, and thus prints that bit pattern as-is. %x
需要一个无符号整数,因此按原样打印该位模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.