c - 为什么在将数字转换为无符号类型时会对其进行符号扩展?

标签 c printf

我正在研究 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 ,结果各不相同。结果是0xFFFFFFF6a , 而 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/

相关文章:

PHP printf 换行符

我可以在 C 中 free() 静态变量和自动变量吗?

python - Gtk 笔记本通过滚动和 <alt>+1 更改页面,如 firefox、chrome、epiphany

android - 使用C程序发送视频文件保存在Android手机上

c - 无法检查 C 中 argv[] 中的第二个字符

c - 如何使用 getaddrinfo 连接到使用外部 IP 的服务器?

c - 向 printf() 添加换行符会更改代码行为

c - 为什么 printf 只显示第一个字母?

c - 为什么使用 asprintf() 而不是 sprintf()?

由于不相关的空 printf 语句,C 程序输出完全改变