R
Rod Pemberton
Wow! This code is really awesome. I think this is the absolute best
way I have seen yet. I will have to study your code and break it down
to see how it works exaclty. Do you think that it could it be placed
within a #define ?
Yes. Just remember that it's only for 'unsigned long' 's which are 32-bits
in length (i.e., rarely it's non-portable). You'd need a different version
for other unsigned types: short, long long, etc. This method won't work
with signed types.
/* BS for byte-swap */
#define BS(a)
(((a)&0xFF000000)>>24)|(((a)&0xFF0000)>>8)|(((a)&0xFF00)<<8)|(((a)&0xFF)<<24
)
/*...*/
unsigned long a,b;
a=0x090a0b0c;
b=BS(a);
Each 'FF' masks off one of the four respective bytes using the '&' bitwise
and operator. This leaves you with four unsigned long each of which has a
byte to be relocated. The '>>' and '<<' bitshift operators move each byte
to it's new position (within an 'unsigned long'). The '|' bitwise or
operator puts all four unsigned long's, each one with one relocated byte,
back together.
1) four unsigned long's (each 'a')
0x090a0b0
0x090a0b0
0x090a0b0
0x090a0b0
2) and masking, four bytes within unsigned longs
0x09000000
0x000a0000
0x00000b00
0x0000000c
3) shifting, relocated byte within unsigned longs
0x00000009
0x00000a00
0x000b0000
0x0c000000
4) or four together
0x0c0b0a09
This actually optimizes very well with most modern compilers.
It also avoids using byte swapping constructs like arrays or unions which
(in my experience) can cause other programming headaches.
Rod Pemberton