On May 16, 5:27 pm, Alan McKenney <alan_mckenn...@[EMAIL PROTECTED]
> wrote:
> If a 32-bit integer is being sent in 4 bytes, msb first,
> there are two ways of reconstructing the value:
>
> A. // only works if host is big-endian
>
> unsigned char *buf = ....
> unsigned long uint32value;
>
> memcpy( &uint32value, buf+ipos, 4 );
>
> B. // works regardles of endianness of your host
>
> uint32value = ( buf[ipos] << 24 ) |
> ( buf[ipos+1] << 16 ) |
> ( buf[ipos+2] << 8 ) |
> buf[ipos+3] ;
>
> I generally use B, to avoid having to worry
> about endianness.
I generally would not use B, to avoid having to worry about poor
performance.
On the other hand, "A", although quite efficient, works only in big-
endian environments - and the goal here is for the source code to be
endian-agnostic.
So, based on the shortcomings of both A and B, it should be possible
to describe the optimal solution, "C". Solution C would combine the
endian-agnosticism of B, with the endian-dependent efficiency of A.
After all, it is not as if the endianness of the machine could ever
change while the program is running. So, although it makes sense to
write a single set of source code that is capable of executing in
either environment, it makes little sense to execute the same machine
code in both environments. There is nothing to be gained by spending
CPU cycles rearranging bytes - when it is certain that the bytes are
already in the proper order.
In fact, Nikolai's post on this thread demonstrates solution C: to
encapsulate endian-dependencies inside a function. For example, C++
programs on OS X are typically compiled twice - once for a big endian
architecture and again for a little endian architecture (and then the
two binaries are merged to create a "universal" binary capable or
running natively on either architecture). So, an OS X implementation
might look something like:
unsigned int uint32value;
stream >> uint32value;
uint32alue = NXSwapBigIntToHost( uint32value );
NXSwapBigIntToHost() swaps uint32value's byte order only when this
source code is compiled for Intel architectures; when compiled for
PowerPC, NXSwapBigIntToHost() is compiled away to nothing. Of course,
the exact name of the byte-swapping routine is not im****tant in this
example - the im****tant point is that the program calls a routine to
(potentially) swap the bytes of the integer value - rather than to
swap the bytes itself.
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm
for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


|