ActiveState Code

Recipe 576401: Integer to binary number converter


The following script converts an unsigned integer into it's little endian binary number equivalent.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import sys

def d2b(a):
    bin = []
    while a:
        bin.append(a%2)
        a /= 2
    return bin[::-1]

def makeInt(string):
	if int(string) < 0:
		print 'Enter a number greater than or equal to 0'
		sys.exit()
	try:
		return int(string)
	except ValueError:
		print "Enter an interger instead of a string"
		sys.exit()

if __name__ == '__main__':
	if len(sys.argv) != 2:
		integer = makeInt(raw_input("Enter integer: "))
	else:
		integer = makeInt(sys.argv[1])
	bin = d2b(integer)
	if len(bin) != 8:
		for x in xrange(8 - len(bin)): bin.insert(0,0)
	print ''.join([str(g) for g in bin])

Comments

  1. 1. At 11:38 a.m. on 3 aug 2008, Steven Bethard said:

    In Python 2.6 and 3.0, this is basically just the "bin" function:

    Python 2.6b2+ (trunk:65157, Jul 20 2008, 11:58:35) [MSC v.1500 32 bit (Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> bin(12)
    '0b1100'
    

    Or you can use the "b" format specifier in the new format() method:

    >>> '{0:b}'.format(12)
    '1100'
    

Sign in to comment