将 128 分配给 c 中的 char 变量 [英] assigning 128 to char variable in c

查看:29
本文介绍了将 128 分配给 c 中的 char 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The output comes to be the 32-bit 2's complement of 128 that is 4294967168. How?

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

推荐答案

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

Compiling your code with warnings turned on gives:

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

告诉您分配 a=128; 在您的平台上没有很好地定义.

which tell you that the assignment a=128; isn't well defined on your plat form.

标准说:

6.3.1.3 有符号和无符号整数

6.3.1.3 Signed and unsigned integers

1 当一个整数类型的值转换为_Bool以外的其他整数类型时,如果该值可以用新的类型表示,则保持不变.

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否则,如果新类型是无符号的,则在新类型可以表示的最大值的基础上反复加减1,直到值在新类型的范围内.

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 否则,新类型是有符号的,值不能在其中表示;结果是实现定义的,或者引发了实现定义的信号.

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.

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

So we can't know what is going on as it depends on your system.

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

However, if we do some guessing (and note this is just a guess):

128 作为 8 位将是 0b1000.0000

128 as 8 bit would be 0b1000.0000

因此,当您调用 printf 并转换为 int 时,将会有一个符号扩展,例如:

so when you call printf where you get a conversion to int there will be a sign extension like:

 0b1000.0000 ==> 0b1111.1111.1111.1111.1111.1111.1000.0000

which - 打印为无符号代表数字 4294967168

which - printed as unsigned represents the number 4294967168

这篇关于将 128 分配给 c 中的 char 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆