If you have come across some code with reference to swab32 or bswap_32 and wondered how it works, here is the answer.
swab32 will probably be a function that calls bswap_32 which will probably be a macro. The macro will probably be defined as:
( (((x) << 24) & 0xff000000u) | (((x) << 8) & 0x00ff0000u) | (((x) >> 8) & 0x0000ff00u) | (((x) >> 24) & 0x000000ffu));
What on Earth does this mean? The key is to break this down. x will be a 32 bit binary input. Let’s take a sample input of:
00000000 00000000 00001111 11111111
x << 24 means take x and shift it 24 places to the right. One way of accomplishing this is to count 24 places from the left, delete it, and pad out 24 0’s to the right. The result will be:
11111111 00000000 00000000 00000000
Next, AND’ing this with 11111111 00000000 00000000 00000000 will give the same result. The net effect is that the 11111111 has been shifted from the right, to the left.
Notice that the ff in the hex mask shifts by 2 to the right each time. Essentially it is doing a 32 bit switcharoo. The final output will be:
11111111 00001111 00000000 00000000
Neat eh?