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:
- We make a mask for the necessary bits (for example, for 2345 bits – 11100001)
- Reset old bits using AND by mask, get 0 in their place
- Prepare new bits (use offset up for positioning)
- Write new bits using OR