简体   繁体   English

从int到char的赋值如何在C中工作?

[英]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 . 在二进制中, 50011111010024411110100

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有符号和无符号整数

  1. When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged. 当具有整数类型的值转换为除_Bool之外的另一个整数类型时,如果该值可以由新类型表示,则它将保持不变。
  2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type. 否则,如果新类型是无符号的,则通过重复地添加或减去一个可以在新类型中表示的最大值来转换该值,直到该值在新类型的范围内。 60) 60)
  3. Otherwise, the new type is signed and the value cannot be represented in it; 否则,新类型将被签名,并且值无法在其中表示; either the result is implementation-defined or an implementation-defined signal is raised. 结果是实现定义的,或者引发实现定义的信号。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM