Search code examples
cbitwise-operatorsbitbit-shift

convert big endian to mid little endian


I have the following big endian in C:

int32_t num = 0x01234567;

I'd like to convert it to mid little endian like this : 0x45670123

How do I use the bitwise operator to do that in C.


Solution

  • A very simple approach would be:

    • Read a byte from num with the AND operator.
    • Shift the read byte to the position you want in the output number.
    • OR the shifted byte with your output number.
    • Repeat until done.

    Example:

    uint32_t num = 0x01234567;
    uint32_t output = 0;
    
    uint32_t firstByte = num & 0xff000000; // firstByte is now 0x01000000
    // Where do we want to have 0x01 in the output number?
    // 0x45670123
    //       ^^ here
    // Where is 0x01 currently?
    // 0x01000000
    //   ^^ here
    // So to go from 0x01000000 to 0x00000100 we need to right shift the byte by 16 (4 positions * 4 bits)
    uint32_t adjByte = firstByte >> 16; // adjByte is now 0x0100
    // OR with output
    output |= adjByte;
    

    AND, Shift & OR operator on wikipedia.