Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I manipulate bits in Python?

Tags:

python

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 ?

like image 814
Eden Avatar asked Sep 29 '08 06:09

Eden


People also ask

How do I toggle a binary bit 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.

How do you slice a bit in Python?

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.


2 Answers

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.

like image 54
Fredrik Johansson Avatar answered Sep 20 '22 19:09

Fredrik Johansson


value = 0xdeadbeef value &= ~(1<<10) 
like image 39
Greg Hewgill Avatar answered Sep 23 '22 19:09

Greg Hewgill