converting decimal to binary

Michael P. Soulier msoulier at storm.ca._nospam
Fri May 23 23:19:49 EDT 2003


On Sat, 24 May 2003 01:20:34 GMT, Raymond Hettinger
<vze4rx4y at verizon.net> wrote:
> 
>>>> def bin(x):
>  d = {0:'000', 1:'001', 2:'010', 3:'011', 4:'100', 5:'101', 6:'110', 7:'111'}
>  return ''.join([d[int(dig)] for dig in oct(x)])
> 
>>>> bin(192)
> '000011000000'
> 
> 
> Anything is a one-liner once someone has written a function
> that directly supports whatever your trying to do :-)
> 
>  There is a trade-off between having builtin support for everything
> versus making it trivially easy to craft a new tool for things
> like binary conversions which don't seem to come-up that
> often.

    True, true. I'm a fan of adding whatever we need to the standard
library, as long as it stays out of the core language. Keep that simple. 

    I did things the hard way, so now I have a one-liner. 

def byte2bits(byte):
    """This function takes a single integer, representing a single byte value,
    and returns a bit-string representing that byte."""
    assert(byte < 256 and byte >= 0)
    bits = ""
    power = 7
    while power >= 0:
        exponential = 2 ** power
        if byte >= exponential:
            bits += '1'
            byte -= exponential
        else:
            bits += '0'

        power -= 1

    assert(len(bits) == 8)
    return bits

    I wanted to ensure 8 bits returned, as this is for network
calculations. That's a clever solution of yours though. 

    Mike

-- 
Michael P. Soulier <msoulier at digitaltorque.ca>, GnuPG pub key: 5BC8BE08
"...the word HACK is used as a verb to indicate a massive amount
of nerd-like effort."  -Harley Hahn, A Student's Guide to Unix
HTML Email Considered Harmful: http://expita.com/nomime.html




More information about the Python-list mailing list