#define SwapByte4(ldata) \
(((ldata & 0x000000FF) << 24) | \
((ldata & 0x0000FF00) << 8) | \
((ldata & 0x00FF0000) >> 8) | \
((ldata & 0xFF000000) >> 24))
What does that 0x000000FF represent? I know that decimal 15 is represented in hex as F, but why is it << 24?
This kind of code tends to be used to swap things between big endian and little endian format. There is also a little trick that will convert a word in some known format (lets say, little endian) into whatever endianness the current machine happens to be, and vice versa. That would go something like this:
This works (assuming I haven't messed it up) because regardless of how bytes are actually stored, shift left is guaranteed to shift towards more significant bits. Converting to a char* allows you to access the bytes in the order they are actually stored in memory. Using this trick you don't need to detect the machine endianness to read/write stuff in a known format. Admittedly you could also just use the standard functions (hton etc.) :P
(Note: You have to be a little careful and cast the char before shifting, otherwise it just overflows all over your shoes. Also, += isn't the only option, |= would probably make more sense but might be less clear if you aren't used to it, I'm not sure)
Here is a hex value, 0x12345678, written as binary, and annotated with some bit positions:
...and here is 0x000000FF:
So a bitwise AND selects just the bottom 8 bits of the original value:
...and shifting it left by 24 bits moves it from the bottom 8 bits to the top:
...which is 0x78000000 in hex.
The other parts work on the remaining 8-bit portions of the input:
so the overall effect is to consider the 32-bit value
ldata
as a sequence of four 8-bit bytes, and reverse their order.You need to look at the
0x000000FF
as a bitmask, i.e. where it's 1 the value ofldata
will be taken and where it's 0 - 0 will be taken.In order to understand the bitmask u need to convert it to binary, with hex it's very easy, every hex number is 4 binary digits, i.e.:
hex 0 = binary 0000 hex 1 = binary 0001 and so on.
Now to shifts: notice that the shift takes some data from the source, 8 bits exactly, and moves it to another location in the destination.
Now note that there's
|
i.e. OR operation on all the bitmask AND operations, i.e. zeroes will stay zeroes and in case there's '1' the result will contain one.Hope it helps :)
Let's say data is a 32 bit number represented as 0x12345678 (each number is 4 bits in hex)
Data & 0x000000FF means keep only the last 8 bits (called a bit mask) = 0x00000078
The << 24 means move this value to the left 24 bits (78 starts at position 24 [0 index]) = 0x78000000
The | means logical or which in this case will just be an addition
Final result = 0x78563412
Read on logical manipulations