Because you type %d , which is for a number. So you have:
u.ch[0] = 3;
which is in binary format
0000 0011 // 8bits, as char is 1B
then you have
u.ch[1] = 2;
which the
0000 0010 // 8bits, as char is 1B
And "when you put 2 and 2 together" (: D)
00..00 0000 0010 0000 0011 // sizeof (int) * 8 bits ^^^^^^ ^^^^^^^^^ ^^^^^^^^^ //(sizeof(int)*8-16)bits this is the 2 this is the 3
which is 515 in dec.
Sorry, I missed the why part. It depends on the platform, you should read about Endianness and, more specifically, about big endians and little-endian. There are several examples in this article. Hint: it seems that you have a car with small ends.
Well, I will summarize my comment here: arrays are guaranteed to be stored in continuous memory. Assume sizeof( int ) == 2 , for a simpler explanation . So you have
u.ch[0] = 3; u.ch[1] = 2;
At first 3 will be saved, and on the next byte 2 will be recorded. SO, how do you (I think) expect memory:
0000 0011 0000 0010 ^^^^3^^^^ ^^^^2^^^^
BUT remember that you are using union ! And you type int . SO, this int has the same bit:
0000 0011 0000 0010
And your cars are little oriented, which translates this:
0000 0010 0000 0011 (reversed order of the bytes!)
What is the binary representation of 515