how 256 stored in char variable and unsigned char(256 如何存储在 char 变量和 unsigned char 中)
问题描述
最多 255,我可以理解整数是如何存储在 char 和 unsigned 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.
这篇关于256 如何存储在 char 变量和 unsigned char 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:256 如何存储在 char 变量和 unsigned char 中
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
