I’m working with some legacy code and I came across a function which is apparently used to perform network byte order conversions on an arbitrarily long field (bigger than ntohl can handle).
I can’t understand it well enough to tell if it’s doing anything more than reversing the byte order over the msg buffer range though (or even if it will do that reliably). Can someone help me break this down and analyze it so I can replace it with something that’s more intelligible (or at least comment it well)!?
void swapit(unsigned char *msg, int length) {
for(;length>0;length--, msg++) {
*msg = ((*msg * 0x0802LU & 0x22110LU) |
(*msg * 0x8020LU & 0x88440LU)) *
0x10101LU >> 16;
}
}
To see how it works, consider applying the operations to the bit pattern
abcdefgh.I’ll represent binary numbers with
.for0, so the non-zero bits stand out.The first subexpression is:
The second is:
Combining them and multiplying by the final constant gives:
Finally shifting down by 16 bits gives
hgfedcba, the reverse of the original pattern.