Big to little

Started by
6 comments, last by doynax 18 years, 6 months ago
//This seems to work It converts a big inedian 32 bit int to Little inedian 32 bit int... but if someone can make sure that it works, that would be good. void BI2LI(int &data) { data = (((data>>28)&0xF)<<4) + ((data>>24)&0xF) + (((data>>20)&0xF)<<12) + (((data>>16)&0xF)<<8) + (((data>>4)&0xF)<<28) + (((data)&0xF)<<24) + (((data>>8)&0xF)<<16) + (((data>>12)&0xF)<<20); }
Insufficent Information: we need more infromationhttp://staff.samods.org/aiursrage2k/
Advertisement
That looks suspiciously like nybble swapping, not byte swapping..
Shouldn't it be something like this:

data = ((data & 0xff000000) >> 24) | // Leftmost -> rightmost       ((data & 0xff0000) >> 8) | // Middle-left -> middle-right       ((data & 0xff00) << 8) | // Middle-right -> middle-left       ((data & 0xff) << 24); // Rightmost -> leftmost


Can't varify that at the moment tho'.
the rug - funpowered.com
or perhaps this is conceptually cleaner:
void swap(int value){int temp = value;for (int i = 0; i < 4; i++){((char *)&value) = ((char *)&temp)[3-i];}}

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

I'd rather just not worry about what endian-ness I'm on, and use the host-to-network conversion functions. (network byte order is big endian)

Host to Network Short: htons()
Host to Network Long: htonl()
Network to Host Short: ntohs()
Network to Host Long: ntohl()

No further work needed, it's portable, and should be optimized accoring to your vendor's tastes.
And leaves you unprepared when you're given input from a file format defined to be little endian when you're on a big endian machine. ex: a UTF-16LE encoded file.
Sorry to interrupt, but what's endian?
------------------------------Support the Blue Skies in Games Campaign!A blog... of sorts.As a general rule, if you don't have a general rule in your signature, you aren't as awesome as someone who does. General rules roxor teh big one one ones.
Quote:Original post by programwizard
Sorry to interrupt, but what's endian?
Wikipedia on Endianness
On Holy Wars and a Plea for Peace

This topic is closed to new replies.

Advertisement