3

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.

2013Asker
  • 2,008
  • 3
  • 25
  • 36
  • @WhozCraig Unsigned integer overflow is defined (it takes the overlflowing value modulo `UINT_MAX + 1`). –  Aug 17 '13 at 23:50
  • @H2CO3 you're correct. unsigned cannot overflow (and I should damn well know that, considering I wrote [this answer](http://stackoverflow.com/questions/13600991/why-is-a-negative-int-greater-than-unsigned-int/13601259#13601259)). – WhozCraig Aug 17 '13 at 23:52
  • @WhozCraig No worries... once I've erroneously stated (for whatever brain dead reason) that type information is not needed for code generation when compiling Objective-C. And despite I've corrected myself within a few minutes, some people still insisted that I have no idea what I am talking about... whatever. –  Aug 17 '13 at 23:54

1 Answers1

8

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
alexsh
  • 1,121
  • 8
  • 12
  • +1 This is correct. It was #3 that I was spacing out on during my momentary lapse of sanity in general-comment. (just had one of *those* days) – WhozCraig Aug 18 '13 at 00:02