Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

binary - How assignment from int to char works in C?

What happens when you assign an int to a char in C? Does it always just ignore the extra bits on the left?

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

In binary, 500 is 111110100 and 244 is 11110100.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 Signed and unsigned integers

  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.
  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)
  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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...