What is the quickest way to reverse the endianness of a 16 bit and 32 bit integer. I usually do something like (this coding was done in Visual Studio in C++):
un
Why aren't you using the built-in swab
function, which is likely optimized better than your code?
Beyond that, the usual bit-shift operations should be fast to begin with, and are so widely used they may be recognized by the optimizer and replaced by even better code.
Because other answers have serious bugs, I'll post a better implementation:
int16_t changeEndianness16(int16_t val)
{
return (val << 8) | // left-shift always fills with zeros
((val >> 8) & 0x00ff); // right-shift sign-extends, so force to zero
}
None of the compilers I tested generate rolw
for this code, I think a slightly longer sequence (in terms of instruction count) is actually faster. Benchmarks would be interesting.
For 32-bit, there are a few possible orders for the operations:
//version 1
int32_t changeEndianness32(int32_t val)
{
return (val << 24) |
((val << 8) & 0x00ff0000) |
((val >> 8) & 0x0000ff00) |
((val >> 24) & 0x000000ff);
}
//version 2, one less OR, but has data dependencies
int32_t changeEndianness32(int32_t val)
{
int32_t tmp = (val << 16) |
((val >> 16) & 0x00ffff);
return ((tmp >> 8) & 0x00ff00ff) | ((tmp & 0x00ff00ff) << 8);
}