Swap byte order of 32-bit Data

From Software Engineers Wiki
Jump to: navigation, search

Swap byte order of 32-bit data.

Answer

Swapping byte order is needed when converting data between big-endian and little-endian format. There are two ways of swapping; one is bit operation and the other is memory swapping bytes in the memory.

void swap32_bits(uint32_t *bytes)
{
        uint32_t data = *bytes;
        data =
                ((data & 0xff000000) >> 24) |
                ((data & 0x00ff0000) >> 8) |
                ((data & 0x0000ff00) << 8) |
                ((data & 0x000000ff) << 24);
        *bytes = data;
}

void swap32_mem(uint32_t *bytes)
{
        uint8_t *data8 = (uint8_t *) bytes;
        uint8_t tmp;

        tmp = data8[0];
        data8[0] = data8[3];
        data8[3] = tmp;

        tmp = data8[1];
        data8[1] = data8[2];
        data8[2] = tmp;
}

x86 architecture provides bswap instruction for byte swapping. The above implementation of swap32_bits() is plain and simple, and compiler understands the purpose of the function. The gcc for x86 replaces the swap32_bits() to use bswap instruction.

On 32-bit ARM architecture,

00000000 <_Z11swap32_bitsPm>:
   0:   e5902000        ldr     r2, [r0]
   4:   e0223862        eor     r3, r2, r2, ror #16
   8:   e1a03423        lsr     r3, r3, #8
   c:   e3c33cff        bic     r3, r3, #65280  ; 0xff00
  10:   e0233462        eor     r3, r3, r2, ror #8
  14:   e5803000        str     r3, [r0]
  18:   e12fff1e        bx      lr

0000001c <_Z10swap32_memPm>:
  1c:   e5d01000        ldrb    r1, [r0]
  20:   e5d0c003        ldrb    ip, [r0, #3]
  24:   e5d03001        ldrb    r3, [r0, #1]
  28:   e5d02002        ldrb    r2, [r0, #2]
  2c:   e5c0c000        strb    ip, [r0]
  30:   e5c01003        strb    r1, [r0, #3]
  34:   e5c02001        strb    r2, [r0, #1]
  38:   e5c03002        strb    r3, [r0, #2]
  3c:   e12fff1e        bx      lr

Reference

Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox