0

For the life of me I cannot figure out how to convert a (maximum) 12-bit number into 2 8-bit bytes (where one of the values will obviously not be able to exceed 4-bits).

For example, I can convert 7 (the 4-bit value) and 60 (8 bit value) integers into 3079 via:
7 + (60 << 8) & 0xfff;

But I cannot reverse this process, extracting 60 and 7 FROM 3079.

I use the following for 16 bits, but I cannot figure out how to modify it for 12-bit values as they do not result in the original value:

(calcMSB << 8) | (calcLSB & 0xff)
user5156141
  • 655
  • 9
  • 29
  • The `60` value isn't right because, as you say, it can't exceed 4 bits (which that value does). Your last statement should work for any bit width between 9 and 16. – 500 - Internal Server Error Dec 13 '19 at 09:44
  • Apologies, the `7` falls into the 4 bit category. Was a late night! – user5156141 Dec 13 '19 at 17:48
  • But why `60 & 0x0F`, then? – 500 - Internal Server Error Dec 13 '19 at 17:52
  • This is the excerpt from existing source code, which I am trying to understand myself - its part of a large lookup table to retrieve the relevant strings. The msb should be the 8 bit value and the lsb should be the 4 bit value. This: `7 + (60 << 8) & 0xfff;` is how they calculate the 12-bit value. – user5156141 Dec 13 '19 at 17:55
  • But that's not right either. If, as you say, the 7 should be in the 4-bit category, then the 8-bit part should be shifted 4 bits to the left to make room, not 8. So pack: `packed = (fourbitpart + (eightbitpart << 4)) & 0xfff`, and unpack: `fourbitpart = packed & 0xF; eightbitpart = packed >> 4;`. – 500 - Internal Server Error Dec 13 '19 at 18:15

1 Answers1

1

Mainly there is no difference between 16 bits and 12 bits here. See pseudocode below:

calcLSB = value12bit & 0xFF; // get LSB byte
calcMSB = value12bit >> 8;    // shift bytes over LSB and take them
VillageTech
  • 1,968
  • 8
  • 18