tags:

views:

1233

answers:

7

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 ?

+6  A: 
value = 0xdeadbeef
value &= ~(1<<10)
Greg Hewgill
+3  A: 

Have you tried copying and pasting your code into the Python REPL to see what will happen?

>>> value = 0xdeadbeef
>>> value &= ~(1<<10)
>>> hex (value)
'0xdeadbaef'
John Millikin
+3  A: 

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

value = 0xDEADBEEF
value &= ~(1<<10)
print value
"0x%08X" % value
Jonathan Leffler
+3  A: 

Python has C style bit manipulation operators, so your example is literally the same in Python except without type keywords.

value = 0xdeadbeef
value &= ~(1 << 10)
Martin W
+16  A: 

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.

fredrikj
A: 
Ross Rogers
+1  A: 

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