"G Patel" <> writes:
> Code in question (assuming CHAR_BIT = 8 system):
>
> union
> {
> unsigned int whole;
> unsigned char bytes[sizeof(int)];
> } var;
>
> var.whole = 0xFF;
>
> if( var.bytes[0] == 0xFF )
> printf("\nLITTLE ENDIAN\n");
> else if( var.bytes[sizeof(int)-1] == 0xFF )
> printf("\nBIG ENDIAN\n");
> else
> printf("\nHUH???\n");
>
> I'm wondering about the portibility of the above ENDIAN tester code
> (don't worry about CHAR_BIT != 8 as an issue).
>
> I've read some really knowledgeable posts on clc before that kept
> emphasizing the fact that C pastes a small abstraction layer over
> memory/hardware. And that 2 contiguous bytes in C's layer is not
> necessarily 2 contiguous in RAM (or process memory space) -or- the
> order of the bytes in C's layer is not necessarily the same as
> hardware. So with this in mind, can the above code be made more
> portable?
I think you're talking about the distinction between physical memory
and virtual memory. On systems with virtual memory, that's all you
can see; it's not possible to access physical memory directly (except
*maybe* by some horribly system-specific low-level technique).
Within a C object, memory is continguous, and addresses of successive
bytes are adjacent. (There are no guarantees across distinct objects,
except that their addresses are unique; any attempt to apply a
relational operator to the addresses of two objects, such as
"&obj1 < &obj2", invokes undefined behavior.)
I'd use "sizeof(unsigned int)" everywhere you used "sizeof(int)",
since you declared the "whole" member as unsigned int. It happens
that int and unsigned int are guaranteed to be the same size, but I
just now had to check the standard to confirm that; if you use
"unsigned int" consistently, the question doesn't arise.
You said not to worry about CHAR_BIT != 8, but I'll still mention that
the code will report LITTLE_ENDIAN if sizeof(unsigned int) == 1 (which
can only happen if CHAR_BIT >= 16). If an int is a single byte, then
it has no meaningful byte ordering.
Apart from that, I think the code will work reliably as long as
unsigned int has no padding bits. If it does have padding bits,
there's a possibility that the 0xFF won't land in either the
high-order or the low-order byte. In that case, printing "HUH???" is
probably good enough.
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.