Newbie: displaying binary numbers
David Goodger
dgoodger at bigfoot.com
Mon Jun 12 23:12:43 EDT 2000
on 2000-06-12 00:55, Steven Adams (adams_s at lab.eng.usyd.edu.au) wrote:
> I'm trying to display integers as binary numbers, I know there are the calls
> for making hexadecimal and octal strings, but couldn't find anything for
> binary?
>
> are there any modules, or operations not in the docs?
>
> all I need is to convert a number to a binary with n bits.
# enjoy!
# --
# David Goodger dgoodger at bigfoot.com Open-source projects:
# - The Go Tools Project: http://gotools.sourceforge.net
# (more to come!)
def bin(number, n=None,
octal={'0':'000','1':'001','2':'010','3':'011', # fixed mapping,
'4':'100','5':'101','6':'110','7':'111'}): # evaluated once
"""Converts an integer to a binary string, optionally fixed-width."""
import string # not needed in 1.6
octstr = oct(number)
if octstr[-1] == 'L': # for long integers
octstr = octstr[:-1]
binstr = string.join(map(octal.get, octstr), "") # in 1.6: "".join()
if n is None: # strip off leading 0's
# takes advantage of: if no match, string.find() returns -1
return binstr[string.find(binstr, '1'):]
# return binstr[binstr.find('1'):] # 1.6
else:
return ("0" * n + binstr)[-n:] # populate with 0's
# some test code:
for i in range(16) + [33, 101, 255, 257, 1001,
2**16-2**15-2**13-2**11-2**9-2**7-2**5-2**3-3,
1010101010101010101010101L]:
print "bin(%s): %s" % (i, bin(i))
print " " * 30 + "bin(%s, 5): %s" % (i, bin(i, 5))
More information about the Python-list
mailing list