Re: platform independent bit shifting
- From: Willem <willem@xxxxxxxx>
- Date: Thu, 28 Dec 2006 15:36:02 +0000 (UTC)
Andrew wrote:
) i'm trying to make sure my program runs on different platforms but don't
) have access to a big-endian system for testing.
)
) the only part of my code that might have anything to do with endianness
) is the part where i have to make sure the multibyte unsigned variables i
) write have the bytes in the proper order (either big-endian or
) little-endian, depending on the situation).
)
) so for example i'm concerned about the following function, is it
) platform-independent? it works on little-endian systems, but i can't
) find any information about whether bit shifting or the '& 0xFF' will
) produce the same results on big-endian systems.
)
) int write732(int image, unsigned value)
) {
) unsigned preparedValue;
)
) preparedValue = value & 0xFF;
) preparedValue <<= 8;
)
) preparedValue |= (value >> 8) & 0xFF;
) preparedValue <<= 8;
)
) preparedValue |= (value >> 16) & 0xFF;
) preparedValue <<= 8;
)
) preparedValue |= (value >> 24);
)
) return writeWrapper(image, &preparedValue, 4);
) }
This function reverses the bytes in the unsigned on both little-endian
and big-endian systems. Is that what you want ?
If not, you may want to look at the htonl() and ntohl() functions,
which are part of the standard C library, AFAIK.
By the way, the safest way to make your program endianess-independent is
to make sure that all operations that input and output bytes (to files or
to the network or whatever) work byte by byte.
SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
.
- Follow-Ups:
- Re: platform independent bit shifting
- From: Roger Willcocks
- Re: platform independent bit shifting
- References:
- platform independent bit shifting
- From: Andrew Smith
- platform independent bit shifting
- Prev by Date: Re: platform independent bit shifting
- Next by Date: Re: question about programming
- Previous by thread: Re: platform independent bit shifting
- Next by thread: Re: platform independent bit shifting
- Index(es):