Revision 2 as of 2005-04-01 01:50:23

Clear message

I'm looking for information on Python bit manipulation.

It seems that there are no modules for performing Python bit manipulation.

I personally want to be able to:

The closest thing I've found is [http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/113799 ASPN: bit-field manipulation.]

I imagine that there are many more manipulations people would like to do with bits.

Manipulations

To integer.

   1 >>> print int('00100001', 2)
   2 33

To hex string. Note that you don't need to use x8 bits.

   1 >>> print "0x%x" % int('11111111', 2)
   2 0xff
   3 >>> print "0x%x" % int('0110110110', 2)
   4 0x1b6
   5 >>> print "0x%x" % int('0010101110101100111010101101010111110101010101', 2)
   6 0xaeb3ab57d55

To character. 8 bits max.

   1 >>> chr(int('111011', 2))
   2 ';'
   3 >>> chr(int('1110110', 2))
   4 'v'
   5 >>> chr(int('11101101', 2))
   6 '\xed'

Characters to integers, but not to strings of 1's and 0's.

   1 >>> int('01110101', 2)
   2 117
   3 >>> chr(int('01110101', 2))
   4 'u'
   5 >>> ord('u')
   6 117

Individual bits.

   1 >>> 1 << 0
   2 1
   3 >>> 1 << 1
   4 2
   5 >>> 1 << 2
   6 4
   7 >>> 1 << 3
   8 8
   9 >>> 1 << 4
  10 16
  11 >>> 1 << 5
  12 32
  13 >>> 1 << 6
  14 64
  15 >>> 1 << 7
  16 128

this is the sort of thing we're looking for:

related modules:

Unable to edit the page? See the FrontPage for instructions.