Quickest way to change endianness

前端 未结 4 455
一整个雨季
一整个雨季 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:10

    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);
    }
    

提交回复
热议问题