DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Base 2 Conversion

09.09.2005
| 6001 views |
  • submit to reddit
        Converting from base 2 to int is easy
>>> int('1010', 2)
10
The opposite is a bit involved.
>>> number = 1000
>>> hex2bin = {"0":"0000", "1":"0001", "2":"0010", "3":"0011",
            "4":"0100", "5":"0101", "6":"0110", "7":"0111",
            "8":"1000", "9":"1001", "A":"1010", "B":"1011",
            "C":"1100", "D":"1101", "E":"1110", "F":"1111"}
>>> "".join([hex2bin[h] for h in '%X'%number]).lstrip('0')
'1111101000'
See the def of toBase2(number) <a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440528>here</a>