从 int 到 char 的赋值如何在 C 中工作? [英] How assignment from int to char works in C?
问题描述
在 C 中将 int 分配给 char 会发生什么?它总是忽略左边的多余位吗?
What happens when you assign an int to a char in C? Does it always just ignore the extra bits on the left?
示例(4 字节 int):
Example (4 bytes int):
unsigned char c = 0;
unsigned int i = 500;
c = i; // c is 244
c = i << 24 >> 24; //c is 244
i = i << 24 >> 24; //i is 244
在二进制中,500
是 111110100
,244
是 11110100
.
In binary, 500
is 111110100
and 244
is 11110100
.
推荐答案
通常情况下,这正是发生的情况.ISO/IEC 9899:2011 标准的第 6.3.1.3 节规定了在这种情况下必须发生的事情:
Typically, this is exactly what happens. Section 6.3.1.3 of the ISO/IEC 9899:2011 standard prescribes what has to happen in this case:
6.3.1.3 有符号和无符号整数
- 当一个整数类型的值转换为另一个整数时_Bool 以外的类型,如果该值可以用新的表示类型,它是不变的.
- 否则,如果新类型是无符号的,则值转换为反复加或减一大于最大值可以用新类型表示,直到值在新类型的范围.60)
- 否则,新类型有符号,值不能代表其中;结果是实现定义的或引发了实现定义的信号.
60) 规则描述的是数学值的算术运算,而不是给定类型表达式的值.
60) The rules describe arithmetic on the mathematical value, not the value of a given type of expression.
您的情况属于上述第 2 项(因为您的角色被声明为未签名).在典型的计算机算术中,结果将与您描述的完全一样.
Your case falls under item 2 above (since your character is declared as unsigned). In a typical computer arithmetic, the result will be exactly as you described.
这篇关于从 int 到 char 的赋值如何在 C 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!