0

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;
}
PowerNow
  • 363
  • 1
  • 2
  • 15
  • 2
    Do you mean you basically want to do `(byte1 << 8) | byte2` or something similar? – Some programmer dude May 05 '22 at 08:07
  • The task looks weird, why would you like to change the bits (not bytes) order? BigEndian <-> LittleEndian is quite common, but this concerns bytes order only. Bits order on the particular machine does not impact binary operations (shift, OR, AND, etc.), they will work all the same regardless of the internal representation. – pptaszni May 05 '22 at 08:25
  • The point is that I get as an input 2 sperate LSB first bytes and have to read the content as an short int value. To I have other possibilities? – PowerNow May 05 '22 at 11:06
  • Endianness is about *byte* ordering, not bit.The bit order of the individual bytes will be the same in both big and little endianness. Reversing bit order makes no sense when converting between big and little endianness. – Some programmer dude May 05 '22 at 11:15

1 Answers1

1

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
Avinash
  • 875
  • 6
  • 20