binary representaion of a number

David Goodger dgoodger at bigfoot.com
Mon Aug 21 00:06:52 EDT 2000


on 2000-08-20 22:48, David Broadwell (dbroadwell at mindspring.com) wrote:

> Deja and the faqts and the docs, haven't quite yeilded what i am looking
> for. And to me it sounds very simple, so perhaps i am missing something.
> 
> I have numbers, that i have pulled in as strings in a file, converted
> them to the actuall object. Now, how do i display or print it as a
> binary string.
> 
>>>> thestring ='3c0f1001'
>>>> i = string.atoi(thestring,16)
>>>> print i
> 1007620097
>>>> hex(i)
> '0x3c0f1001'
>>>> oct(i)
> '07403610001'
> 
> here is what i am looking for:
>>>> bin(i)
> '111100000011110001000000000001'
> 
> Help - ideas?

I posted this in June:

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