c - 将128分配给c中的char变量

标签 c char signed

输出结果是 128 的 32 位 2 的补码,即 4294967168。如何?

#include <stdio.h>
int main()
{
    char a;
    a=128;
    if(a==-128)
    {
        printf("%u\n",a);
    }
    return 0;
}

最佳答案

在打开警告的情况下编译代码会给出:

warning: overflow in conversion from 'int' to 'char' changes value from '128' to '-128' [-Woverflow]

这告诉您作业 a=128; 在您的平台上没有明确定义。

标准说:

6.3.1.3 Signed and unsigned integers

1 When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.

2 Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

3 Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

所以我们不知道发生了什么,因为这取决于您的系统。

但是,如果我们进行一些猜测(注意这只是一个猜测):

128 作为 8 位将是 0b1000.0000

因此,当您调用 printf 时,您会得到一个转换为 int 的符号扩展名,例如:

 0b1000.0000 ==> 0b1111.1111.1111.1111.1111.1111.1000.0000

其中 - 打印为无符号表示数字 4294967168

关于c - 将128分配给c中的char变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51047929/

相关文章:

java - 24 位 wav 文件的数据 block 有符号字节还是无符号字节?

c - 二维字符数组的 malloc 函数的段错误

C - 轻松将 void** 转换为 char* 吗?

c - 字节数组的 itoa 函数

c - 为什么这个循环在 c 中运行无限次?

assembly - 汇编中的 16 位乘法?

c - 链接到 C 中的特定库时运行时精度损失

c - 如何在 C 程序中读取一行并拆分为字符串和浮点值?

c - 从套接字 recv() 到 uint16_t 的 memcpy 上的段错误

java - 已签名的 Java Applet 在连接到 Web 服务时抛出安全异常