256如何存储在char变量和无符号char中 [英] how 256 stored in char variable and unsigned char

查看:440
本文介绍了256如何存储在char变量和无符号char中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最多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\n",a);
        return(0);
}

在上面的代码中,我为未签名字符 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?

推荐答案

您的猜测是正确的.转换为无符号类型使用模块化算法:如果该值超出范围(太大或为负),则将其模2 N 进行模降低,其中N是目标类型中的位数.因此,如果char具有8位(通常),则该值将以256为模进行缩减,以使256变为零.

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.

这篇关于256如何存储在char变量和无符号char中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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