[英]How assignment from int to char works in C?
What happens when you assign an int to a char in C? 当您在C中将int分配给char时会发生什么? Does it always just ignore the extra bits on the left?
是否总是只忽略左侧的多余位?
Example (4 bytes int): 示例(4字节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
In binary, 500
is 111110100
and 244
is 11110100
. 在二进制中,
500
是111110100
和244
是11110100
。
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:
ISO / IEC 9899:2011标准的第6.3.1.3节规定了在这种情况下必须发生的事情:
6.3.1.3 Signed and unsigned integers 6.3.1.3有符号和无符号整数
60) The rules describe arithmetic on the mathematical value, not the value of a given type of expression. 60)规则描述了数学值的算术,而不是给定类型表达式的值。
Your case falls under item 2 above (since your character is declared as unsigned). 您的案件属于上述第2项(因为您的角色被宣布为无符号)。 In a typical computer arithmetic, the result will be exactly as you described.
在典型的计算机算术中,结果将与您描述的完全一致。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.