Quickest way to change endianness

前端 未结 4 464
一整个雨季
一整个雨季 2021-02-06 17:33

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         


        
4条回答
  •  执念已碎
    2021-02-06 18:32

    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
    

提交回复
热议问题