A Programming Puzzle

Explain the output. (On my computer I get a single linebreak.)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std;

union X {
	char y[4];
	unsigned int z;
} x = {"LOL"}; //4C 4F 4C 00

X f(X x) {
	x.z <<= 8;
	return x;
}

ostream& operator<<(ostream &out, const X &x) {
	return out << x.y;
}

int main(int argc, char *argv[]) {
	cout << f(x) << endl;
	return 0;
}

Edit: This is just for fun, I don't need "help."
(Ee... Maybe "fun" should be in quotes too.)
Last edited on
endianness (little-endian in your case)
What does line 11 mean exactly?
closed account (1vRz3TCk)
What does line 11 mean exactly?

<<= is Bitwise left shift assignment
Gaminic wrote:
What does line 11 mean exactly?
 
x.z = x.z << 8; //bit shift x.z 8 bits left then store that new bit pattern in x.z 


@ne555: Right. So then, what would this print out, if stored in big-endian format? What could I change in my code to mimic that behavior even though I am instead storing in little-endian format?
If you set it to "ABC" then it will be stored.
'A' 'B' 'C' '\0'
Little endian reads from right to left (3258), big endian left to right (43968).
So if you multiply by 2^8 ("left" shift)
1
2
'\0' 'A' 'B' 'C' // little endian 52128
'B' 'C' '\0' '\0' // big endian 48128 
So in different systems they are different numbers, so you can't use bit-shift (arithmetic operation) and expect the same result.

I think that you shouldn't worry about endianness except in the serialization
http://www.cplusplus.com/forum/general/2417/#msg9352
Topic archived. No new replies allowed.