256 如何存储在 char 变量和 unsigned char 中

2022-01-12 00:00:00 memory c char bits c++

最多 255,我可以理解整数是如何存储在 charunsigned char 中的;

Up to 255, I can understand how the integers are stored in char and unsigned char ;

#include<stdio.h>
int main()
{
        unsigned char a = 256;
        printf("%d
",a);
        return(0);
}

在上面的代码中,我为 unsigned char 和 char 输出了 0.

In the code above I have an output of 0 for unsigned char as well as char.

对于256我认为是代码中整数的存储方式(这只是猜测):

For 256 I think this is the way the integer stored in the code (this is just a guess):

第一个 256 转换为二进制表示,即 100000000(共 9 位).

First 256 converted to binary representation which is 100000000 (totally 9 bits).

然后他们删除删除 最左边的位(设置的位),因为 char 数据类型只有 8 位内存.

Then they remove the remove the leftmost bit (the bit which is set) because the char datatype only have 8 bits of memory.

所以它在内存中存储为 00000000 ,这就是为什么它打印 0 作为输出.

So its storing in the memory as 00000000 , that's why its printing 0 as output.

猜测正确还是有其他解释?

Is the guess correct or any other explanation is there?

推荐答案

你猜对了.转换为无符号类型使用模运算:如果值超出范围(太大或负数),则以 2N 为模减少,其中 N 是目标类型中的位数.因此,如果(通常情况下)char 有 8 位,则该值以 256 为模减少,因此 256 变为 0.

Your guess is correct. Conversion to an unsigned type uses modular arithmetic: if the value is out of range (either too large, or negative) then it is reduced modulo 2N, where N is the number of bits in the target type. So, if (as is often the case) char has 8 bits, the value is reduced modulo 256, so that 256 becomes zero.

请注意,转换为有符号类型没有这样的规则 - 超出范围的值会给出实现定义的结果.另请注意,char 未指定为正好 8 位,在不太主流的平台上可以更大.

Note that there is no such rule for conversion to a signed type - out-of-range values give implementation-defined results. Also note that char is not specified to have exactly 8 bits, and can be larger on less mainstream platforms.

相关文章