pleslie
pleslie

Reputation: 87

Writing Bits across two bytes

I have a requirement where I have to write a HEX value to an 11 bit "container" across two bytes. The layout is as follows: Byte 5(bit 3) is the lsb and data goes to Byte 4(bit 5)which is the msb. What is the best method for writing data to the bit locations in question.

For example if I need to write the value 0x1DA to these locations what would be the best way of doing that while keeping the bit ordering correct.

FYI the is for CAN communication for an 8 byte CAN message.

I was thinking of doing this:

_templsb = DatatoWrite & 0x1F;
_templsb <<= 3;
Byte5 &= ~0xF8;
Byte5 = Byte5 | _templsb;

_tempmsb = DatatoWrite & 0x7E0;
_tempmsb >>= 5;
Byte4 &= ~0x3F;
Byte4 =  Byte4 | _tempmsb;

Is something like this the best way to do it?

Upvotes: 2

Views: 474

Answers (1)

Clifford
Clifford

Reputation: 93486

To be clear, it appears that the following arrangement is what you wish to achieve:

enter image description here

So that for your example 0x01DA, the transform would be:

  • Byte4 = 0x0E
  • Byte5 = 0xD0

That being the case, then:

uint16_t Word = 0x1DA ;
uint8_t Byte4 = (Word & 0x07E0) >> 5 ;
uint8_t Byte5 = (Word & 0x001F) << 3 ;

If the unused bits in Byte4 and Byte5 already contain data that must remain unchanged, then:

Byte4 = (Byte4 & 0xC0) | (Word & 0x07E0) >> 5 ;
Byte5 = (Byte5 & 0x07) | (Word & 0x001F) << 3 ;

Upvotes: 1

Related Questions