c++ – How to fill an area in a byte?

Question:

Let's say there is a byte 0b00001000 , for convenience I will divide it: 0 b 0000 - 1000

How to fill an area in a byte with your number?

Here is an example, from 1 to 4 bits you need to write 0011 , it will come out:

0 b 000 0 – 011 0

Or from 0 to 1 you need to write 11 , it will come out:

0 b 0000 – 10 11

Answer:

  1. We make a mask for the necessary bits (for example, for 2345 bits – 11100001)
  2. Reset old bits using AND by mask, get 0 in their place
  3. Prepare new bits (use offset up for positioning)
  4. Write new bits using OR
Scroll to Top