[Tutor] bitwise manipulation

Tim Johnson tim at johnsons-web.com
Fri Dec 9 03:20:15 CET 2005


* John Fouhy <john at fouhy.net> [051208 16:55]:
> 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?
 
  OK

> [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)
 
  You just did most of the work for me!

> Note that integers are immutable, so there's no way to change an existing int.
 
  That's what objects are for...

> Also, if you're playing with stuff at that level, you might find the
> struct module helpful.
 
  I believe it would.
  Thanks
  I will call the class Bitters ....

  cheers
  Tim (off to brew some Bitters)
  
> --
> John.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Tim Johnson <tim at johnsons-web.com>
      http://www.alaska-internet-solutions.com


More information about the Tutor mailing list