d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > C Reverse Bytes
Add Reply New Topic New Poll
Member
Posts: 24,101
Joined: Nov 8 2007
Gold: 5,561.70
Sep 24 2012 04:03pm
So i was looking at an example of a function to reverse the bytes of an unsigned 4 byte int

I don't exactly understand how they figured out their shifts? Can someone explain the thought process behind this?

The function works like this: for int x = 0x12345678 it will return 0x78563412.

Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Sep 24 2012 04:24pm
write out all 4 bytes of x in binary. for each section in the above, underline the result from the original x and watch as it moves.

i haven't done it since i dont care enough to, but that's generally how to solve bit shifting problems unless it's one of those annoying esoteric ones. especially since you already have the solution
Member
Posts: 24,101
Joined: Nov 8 2007
Gold: 5,561.70
Sep 24 2012 07:57pm
Yeah I actually made a picture of it, figured it out thanks!
Member
Posts: 9,803
Joined: Jun 28 2005
Gold: 6.67
Sep 25 2012 06:20am
That's ugly.

here's a much clearer version:
Code
inline void
BSWAP(uint32_t & val)
{
val = ((val & 0x000000FF) << 24)|
   ((val & 0x0000FF00) <<  8)|
   ((val & 0x00FF0000) >>  8)|
   ((val & 0xFF000000) >> 24);
}


or as an image:


This post was edited by KrzaQ2 on Sep 25 2012 06:21am
Member
Posts: 24,101
Joined: Nov 8 2007
Gold: 5,561.70
Sep 25 2012 10:02am
Nvm

This post was edited by lopelurag on Sep 25 2012 10:12am
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll