Skip to content Skip to sidebar Skip to footer

How Do I Manipulate Bits In 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 ?

Solution 1:

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.

Solution 2:

value = 0xdeadbeef
value &= ~(1<<10)

Solution 3:

Some common bit operations that might serve as example:

defget_bit(value, n):
    return ((value >> n & 1) != 0)

defset_bit(value, n):
    return value | (1 << n)

defclear_bit(value, n):
    return value & ~(1 << n)

Usage e.g.

>>>get_bit(5, 2)
True
>>>get_bit(5, 1)
False
>>>set_bit(5, 1)
7
>>>clear_bit(5, 2)
1 
>>>clear_bit(7, 2)
3

Solution 4:

You should also check out BitArray, which is a nice interface for dealing with sequences of bits.

Solution 5:

Omit the 'unsigned long', and the semi-colons are not needed either:

value = 0xDEADBEEF
value &= ~(1<<10)
print value
"0x%08X" % value

Post a Comment for "How Do I Manipulate Bits In Python?"