Convert Little Endian to Big Endian

前端 未结 13 1831
慢半拍i
慢半拍i 2020-11-27 16:34

I just want to ask if my method is correct to convert from little endian to big endian, just to make sure if I understand the difference.

I have a number which is st

13条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 16:46

    OP's code is incorrect for the following reasons:

    • The swaps are being performed on a nibble (4-bit) boundary, instead of a byte (8-bit) boundary.
    • The shift-left << operations of the final four swaps are incorrect, they should be shift-right >> operations and their shift values would also need to be corrected.
    • The use of intermediary storage is unnecessary, and the code can therefore be rewritten to be more concise/recognizable. In doing so, some compilers will be able to better-optimize the code by recognizing the oft-used pattern.

    Consider the following code, which efficiently converts an unsigned value:

    // Swap endian (big to little) or (little to big)
    uint32_t num = 0x12345678;
    uint32_t res =
        ((num & 0x000000FF) << 24) |
        ((num & 0x0000FF00) << 8) |
        ((num & 0x00FF0000) >> 8) |
        ((num & 0xFF000000) >> 24);
    
    printf("%0x\n", res);
    

    The result is represented here in both binary and hex, notice how the bytes have swapped:

    ‭0111 1000 0101 0110 0011 0100 0001 0010‬
    
    78563412
    

    Optimizing

    In terms of performance, leave it to the compiler to optimize your code when possible. You should avoid unnecessary data structures like arrays for simple algorithms like this, doing so will usually cause different instruction behavior such as accessing RAM instead of using CPU registers.

提交回复
热议问题