Binary numeral conversion (Python)

From LiteratePrograms
Jump to: navigation, search

It is easy to create an integer from a binary numeral in Python. The expression

int("10111001", base=2)

evaluates to 185 as expected. However, Python has no built-in support for going the other way: displaying an integer in binary.

Python does have the ability to display an integer in hexadecimal (with "%x" % n). We can utilize this to produce the binary representation by translating the hexadecimal digits one by one. We create a lookup table:

<<lookup table>>=
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'}

The implementation is straightforward:

<<main function>>=
def bin(n):
    if n < 0:
        return "-" + bin(-n)
    # Build list of groups of four binary digits
    s = [hex2bin[hexdigit] for hexdigit in ("%x" % n)]
    # Merge list to single string and remove leading zeros
    s = "".join(s).lstrip("0")
    return s or "0"

A simple test driver:

<<test>>=
if __name__ == "__main__":
    for i in range(-50, 50):
        assert i == int(bin(i), 2)
<<binary.py>>=
lookup table
main function
test
Download code
hijacker
hijacker
hijacker
hijacker