我正在研究 C 如何通过位模式将数据存储在内存中。
但是,当涉及到 printf
时,我遇到了一些问题。格式化。
我已将变量保存为 -10
(我确实理解二进制补码)
另一个变量为 246
.这两个变量的位模式为 11110110
(这是 0xF6
)。
我试图使用 unsigned int
打印出一个值printf
中的十六进制格式.
char a = -10;
unsigned char b = 246;
printf("a : %x , b : %x\n" , (unsigned int) a, (unsigned int) b);
//a : fffffff6 , b : f6
两个整数具有相同的位模式
0xF6
.但是,如果我确实将类型转换为 unsigned int
,结果各不相同。结果是0xFFFFFFF6
为 a
, 而 b
保持原样。对于签名字符,在我看来,类型转换过程使
unsigned char
成一个整数,并用 1 填充所有空位。这是因为他们的签名吗?或者这只是未定义的行为?
最佳答案
在这个表达式中
(unsigned int) a
整数提升应用于对象 a
.来自 C 标准(6.3.1.1 bool 值、字符和整数)
2 The following may be used in an expression wherever an int or unsigned int may be used:
— An object or expression with an integer type (other than int or unsigned int) whose integer conversion rank is less than or equal to the rank of int and unsigned int.
— A bit-field of type _Bool, int, signed int, or unsigned int.
If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. 58) All other types are unchanged by the integer promotions.
和
3 The integer promotions preserve value including sign. As discussed earlier, whether a ‘‘plain’’ char is treated as signed is implementation-defined.
如果你想在转换后的结果对象中,字符对象将被表示为具有类型
unsigned char
那么你必须写(unsigned char) a
作为提升表达式的值 (unsigned char) a
可以用类型 unsigned int
表示那么不需要第二次转换(到 unsigned int
)。 C 标准允许使用参数 pf 类型 int
而不是类型 unsigned int
如果该值以两种类型表示。你可以写printf("a : %x , b : %x\n" , (unsigned char) a, (unsigned int) b);
关于c - 为什么在将数字转换为无符号类型时会对其进行符号扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58503202/