unsigned int x = 0x01020304;
unsigned char *c = (unsigned char*)&x;
Assume x is stored at 0x100. On a little endian architecture (x86, most modern ARM systems, etc), it will be stored in memory as [04][03][02][01], from bytes 0x100 to 0x103. If you assign char c to the address of x (0x100), it will read one byte, which is 0x4.However, on a big endian system, that same value would be stored in memory as [01][02][03][04] - so, reading a byte at 0x100 would return 0x1.
Older ARM systems were big endian, and there are others that run that way, though it's rarer than it used to be. One of the perks of little endian is that if you want to read a smaller version of a value, you can read from the same address. To read that value as an 8, 16, or 32 bit value, I read at the same address. On a big endian system, I'd have to do more address math to do the same thing. It mostly doesn't matter, but it is nice to be able to have a "read of 8 bits at the address of the variable" do the sane thing and return the low order 8 bits, not the high order bits.
To do what you're asking, you'd do something like this:
unsigned char c = (unsigned char)x;
That will give you the low order byte of x. But to do that, on a big endian system, when you've told it to get you the byte at the base address of x, is simply wrong behavior. At least in C. I can't speak to higher level languages since I don't work in them.Unless, I suppose, sizeof was negative :).
Since this compiles to FF 00 00 00 in big-endian and 00 00 00 FF in little-endian, it would work on both platforms.
If you’re reading a file in binary format from disk, though, you always have to know whether the byte you are reading is little-endian or big-endian on disk.
You need to use a bit mask in order to make this code endian-independent rather than a pointer alias. Like (uint8_t)(int & 0xFF), or something like that.
And in the embedded space I think PowerPC and MIPS are still around.
I recently had an interview and a "skill test" in C. It was proctored by the interviewer in-person. I had so many questions about the questions. It was like, what is the output of "some code" and while obvious, there were some questions where specific CPU architecture mattered:
I was like, what architecture are we running on here? So, I answered that "it depends" and explained how it would depend on the architecture. They came back and said that I didn't know C.Sure, whatever. Probably dodged a bullet.