This wiki is in the process of being archived due to lack of usage and the resources necessary to serve it — predominately to bots, crawlers, and LLM companies. Edits are discouraged.
Pages are preserved as they were at the time of archival. For current information, please visit python.org.
If a change to this archive is absolutely needed, requests can be made via the infrastructure@python.org mailing list.

Here is some information and goals related to Python bit manipulation, binary manipulation.

Some tasks include:

Relevant libraries include:

Some simple code is at ActiveState Code Recipes: Bit-field manipulation (in Python 2 syntax).

Here are some other examples.

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