I am using C to implement a packet stream that will be sent out via wireless and am stuck at the following problem. I have an unsigned int 2 bytes long, in the following format in binary:
XXXX YYYY XXXX XXXX, where X & Y’s are bits.
Looking at the format above, I need to just changed the YYYY bits and leave the other bits alone in the packet structure.
I have tried bit shifting and masking, but nothing seems to work.
I am not looking for just a solution so I can copy/paste. I want to learn the methods on how to get it to work and finally decided to post here.
Any help or guidance in the correct direction would be great.
Thanks!
Let’s say you want to replace the YYYY bits with ZZZZ.
Firstly you need to clear the YYYY bits in the original value. This can be done with:
which gives you
XXXX 0000 XXXX XXXX.Next you need to take the new ZZZZ bits and shift them to the left, with:
which gives
0000 ZZZZ 0000 0000.Finally you need to combine the two values, using the or operator:
which gives you
XXXX ZZZZ XXXX XXXX.