Given a series of bits, what's the best way to overwrite a particular range of them.
For example, given:
0100 1010
Say I want to overwrite the middle 2 bits with 10 to make the result:
0101 0010
What would be the best way of doing this?
At first, I thought I would just shift the overwriting bits I want to the correct position (10000), and then use a bitwise OR. But I realized that while it preserves the other bits, there's no way of specifying which bits I want to actually overwrite.
I was looking into Python's bitarray module, but I just want to double-check that I'm not looking over an extremely simple bitwise operation to do this for me.
Thanks.
This is done by first masking the bits you want to erase (forcing them to zero while preserving the other bits) before applying the bitwise OR.
Use a bitwise AND with the pattern (in this case) 11100111
.
If you already have a "positive" version of the pattern (here this would be 00011000
), which is easier to generate, you can obtain the "negative" version 11100111
using what is called 1's complement, available as ~
in Python and most languages with a C-like syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With