I have an integer with a value 7
(0b00000111
) And I would like to replace it with a function to 13
(0b00001101
). What is the best algorithm to replace bits in an integer?
For example:
set_bits(somevalue, 3, 1) # What makes the 3rd bit to 1 in somevalue?
Setting a bitUse the bitwise OR operator ( | ) to set a bit. number |= 1UL << n; That will set the n th bit of number . n should be zero, if you want to set the 1 st bit and so on upto n-1 , if you want to set the n th bit.
The approach to update the bit at the given position is first to clear the bit at the given position and then perform a Binary AND operation to update the bit. Take Input a number N, bit to update as 'bit' and position or index on which we have to update the bit as 'position'.
You can use binary AND and OR to toggle the fourth bit. To set the fourth bit on x, you would use x |= 1<<3; , 1<<3 being a left shift of 0b0001 by three bits producing 0b1000.
These work for integers of any size, even greater than 32 bit:
def set_bit(value, bit): return value | (1<<bit) def clear_bit(value, bit): return value & ~(1<<bit)
If you like things short, you can just use:
>>> val = 0b111 >>> val |= (1<<3) >>> '{:b}'.format(val) '1111' >>> val &=~ (1<<1) '1101'
You just need:
def set_bit(v, index, x): """Set the index:th bit of v to 1 if x is truthy, else to 0, and return the new value.""" mask = 1 << index # Compute mask, an integer with just bit 'index' set. v &= ~mask # Clear the bit indicated by the mask (if x is False) if x: v |= mask # If x was True, set the bit indicated by the mask. return v # Return the result, we're done. >>> set_bit(7, 3, 1) 15 >>> set_bit(set_bit(7, 1, 0), 3, 1) 13
Note that bit numbers (index
) are from 0, with 0 being the least significant bit.
Also note that the new value is returned, there's no way to modify an integer "in place" like you show (at least I don't think so).
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