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
I used the following code for the 16bit version swap function:
_int16 changeEndianness16(__int16 val)
{
return ((val & 0x00ff) << 8) | ((val & 0xff00) >> 8);
}
With g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5 the above code when compiled with g++ -O3 -S -fomit-frame-pointer test.cpp
results in the following (non-inlined) assembler code:
movzwl 4(%esp), %eax
rolw $8, %ax
ret
The next code is equivalent but g++ is not as good at optimizing it.
__int16 changeEndianness16_2(__int16 val)
{
return ((val & 0xff) << 8) | (val >> 8);
}
Compiling it gives more asm code:
movzwl 4(%esp), %edx
movl %edx, %eax
sarl $8, %eax
sall $8, %edx
orl %edx, %eax
ret