Title: What is the behavior of an unsigned int converted to an unsigned char in the C99 standard?
Tags: c;casting;c99;endianness;type-conversion
Question: For example:

```#include <stdio.h&gt;

int main(void){
    unsigned int x = 64;
    x += 1023;

    unsigned char y = x;

    printf("%u\n", y);
    return 0;
}
```

The variable ```y``` holds the value ```63``` on my machine. Does the C99 standard guarantee that the least significant byte will be stored when an unsigned int is converted to an unsigned char, or does the endianness of the machine affect the convertion?

Comment: It should print 63, not 65.

Comment: A quibble: There is no cast in your program. A cast is an operator that performs an explicit conversion; it consists of a parenthesized type name. You have an implicit conversion (which behaves the same way an explicit cast `unsigned char y = (unsigned char)x;` would).

Comment: @wildplasser Oops I misread the output of my program.

Comment: @KeithThompson Thanks for the semantic correction.

Here is the accepted answer: The standard says this about converting to an unsigned type:

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

Which is a fancy way of saying the value wraps around if it doesn't fit. So in your case you'll always get 63, on all machines, unless your ```unsigned char``` can actually store more than 255: it has nothing to do with endianness.

Comment for this answer: @R.. True, I added that bit.
Comment for this answer: Mathematically speaking, would the wrapped value be equivalent to the least significant byte?
Comment for this answer: Modulo by 256 (or the respective max value of unsigned char + 1) appears to truncate the higher bytes, so I suspect only the least significant byte is evaluated in the end.

Here is another answer: Endianness does not matter for the cast. Only the C value matters.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 4, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2013:00:03/27/13', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<c><casting><c99><endianness><type-conversion>', 'Title': 'What is the behavior of an unsigned int converted to an unsigned char in the C99 standard?', 'ViewCount': 313, 'id': 15669761, 'user_AboutMe': '<p>Information wants to be free.</p>\n', 'user_AccountId': 2019841.0, 'user_DisplayName': 'Vilhelm Gray', 'user_Reputation': 11078.0, 'user_Views': 713.0, 'user_id': 1806289.0}}