Thread: changing byte order of an unsigned long?

1. changing byte order of an unsigned long?

Hi all, i'm a newbie to this forum so be gentle!

I have a problem i've spent quite a bit of time tinkering with and can't seem to get anywhere.

I'm trying to write code that takes an unsigned long and reverses the order of the bytes.

For example changing B1B2B3B4 to B4B3B2B1.

Like i said i'm not getting anywhere with this so could anyone at least point me in the right direction?

Thanks
Stu

2. Well to extract B2, you would do
b2 = ( var >> 16 ) & 0xFF;

To put it back in the new position
result = result | ( b2 << 8 );

3. ...and if you don't understand a bit of that, then just google "Bitwise operations"

...and by the way, Salem, your new user title is genius.

4. These may also be of interest:

htonl, htons, ntohl, ntohs - convert values between host and network byte order

5. Hi Salem,

I've had a play with bitwise ops and i can do what you suggested to extract they bytes, but i can't put them back in the reverse order like i'm trying to do.

I also have a problem in that if one of the bytes is 0xF or less, i have a zero which disappears. I.e 0F is displayed as F.

So when i reorder the bytes the final number might not look right, see below.

number F54C09A1 -> in reverse order would be A1094CF5

but the zero disappears when i take 0900 out of F54C09A1.

If you just print with %x, then leading zeros will be suppressed.
Try %04x or %08x

7. Thanks Salem,

I've got it sorted now. I had to use %02x.

Code:
```b1 = ( input_val >> 24 ) & 0xFF;	//Splitting the bytes
b2 = ( input_val >> 16 ) & 0xFF;
b3 = ( input_val >> 8 ) & 0xFF;
b4 = ( input_val >> 0 ) & 0xFF;

printf("\nCorrect order is: %02x%02x%02x%02x", b4,b3,b2,b1);	//rearranging the bytes in reverse order.```