Search code examples
c++bytebitendianness

How to read in C++ a short int (2 byte) LSB first value?


How can I read two separate bytes each with LSB first?

2 speparate LSB first bytes -> one short int MSB first

e.g. 01001100 11001100 -> 00110010 00110011

short int lsbToMsb(char byte1, char byte2) {

  ...
  return msb;
}

Solution

  • Try this:

    char reverseBits(char byte)
    {
        char reverse_byte = 0;
        for (int i = 0; i < 8; i++) {
            if ((byte & (1 << i)))
                reverse_byte |= 1 << (7 - i);
        }
        return reverse_byte;
    }
    short int lsbToMsb(char byte1, char byte2) {
        byte1 = reverseBits(byte1);
        byte2 = reverseBits(byte2);
        short int msb = (byte1 << 8) | byte2;
        return msb;
    }
    
    int main(){
        char byte1 = 76;    // 01001100
        char byte2 = -52;   // 11001100
        short int msb = lsbToMsb(byte1, byte2);
        printf("%d", msb);
        
    }
    

    Output:

    12851   // 00110010 00110011