Converting an integer base 10 to a binary number

Bob Kline bkline at rksystems.com
Thu Mar 29 11:18:13 EST 2001


On Thu, 29 Mar 2001, Daniel Klein wrote:

> 
> def toBinary(dec):
> 	bin = ''
> 	for x in range(8):
> 		bin = str(dec % 2) + bin
> 		dec = int(dec/2)
> 	return bin
> 
> >>> toBinary(32)
> '00100000'
> 
> Of course this only works for 0 <= dec <= 255

No need for that limitation:

$ cat toBinary.py
def toBinary(dec):
    bin = ''
    while dec:
        bin = (dec % 2 and '1' or '0') + bin
        dec = long(dec/2)
    return bin or '0'

if __name__ == "__main__":
    import sys
    dec = len(sys.argv) > 1 and long(sys.argv[1]) or 2 ** 10
    print toBinary(dec)
$ toBinary.py
10000000000
$ toBinary.py 10000000000000000000000
10000111100001100111100000110010011011101010110010010000000000000000000000

You might - for the sake of efficiency - want to have an int-specific
version for cases in which you knew the value would fall within range.

-- 
Bob Kline
mailto:bkline at rksystems.com
http://www.rksystems.com





More information about the Python-list mailing list