In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so:
unsigned long value = 0xdeadbeef; value &= ~(1<<10);
How do I do that in Python ?
We can toggle a bit by doing XOR of it with 1 (Note that 1 ^ 0 = 1 and 1 ^ 1 = 0). The idea is to take a number temp with only one bit set. One by one move the only set bit of temp to left and do XOR of it with n until it crosses MSB (Most Significant Bit) of n.
We need to start extracting k bits from starting position p from right, that means end index of extracted sub-string will be end = (len(binary) – p) and start index will be start = end – k + 1 of original binary string. Convert extracted sub-string into decimal again.
Bitwise operations on Python ints work much like in C. The &
, |
and ^
operators in Python work just like in C. The ~
operator works as for a signed integer in C; that is, ~x
computes -x-1
.
You have to be somewhat careful with left shifts, since Python integers aren't fixed-width. Use bit masks to obtain the low order bits. For example, to do the equivalent of shift of a 32-bit integer do (x << 5) & 0xffffffff
.
value = 0xdeadbeef value &= ~(1<<10)
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