[Tutor] bitwise manipulation

John Fouhy john at fouhy.net
Fri Dec 9 02:43:57 CET 2005


On 09/12/05, Tim Johnson <tim at johnsons-web.com> wrote:
> Are there any python resources available that can make setting/unsetting
> bits directly? I used to do that in "C" with preprocessor macros that
> made calls like set_bit(vInteger,bit_position)
> and unset_bit(vInteger,bit_position).

Well, you could write them yourself?

[untested]

def set_bit(i, n):
    return i | (1 << n)

def unset_bit(i, n):
    return i & ~(1 << n)

def test_bit(i, n):
    return i & (1 << n)

Note that integers are immutable, so there's no way to change an existing int.

Also, if you're playing with stuff at that level, you might find the
struct module helpful.

--
John.


More information about the Tutor mailing list