Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to overwrite some bits in a particular range

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.

like image 305
julian Avatar asked Aug 05 '10 13:08

julian


1 Answers

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.

like image 198
Pascal Cuoq Avatar answered Oct 05 '22 16:10

Pascal Cuoq