[Tutor] Bits operations [another version of binary() using hex()]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri Jul 11 22:33:01 2003


On Fri, 11 Jul 2003, Alan Gauld wrote:

>
> > >octal and hexa...). It's easier to see something like 00101001B...
> >
> > Nope. I pestered Guido about that in Charleroi during EuroPython, and
> > he was determined there was no practical use for it. If you really
> > want it, pester him on Python-dev! :)

Hi Alan,


We already have hex(), which almost does the trick.  If we really wanted a
binary() function, we can write it like this:


###
def binary(x):
    'Returns the binary representation of x.'
    binary_mapping = {'0' : '0000',
                      '1' : '0001',
                      '2' : '0010',
                      '3' : '0011',
                      '4' : '0100',
                      '5' : '0101',
                      '6' : '0110',
                      '7' : '0111',
                      '8' : '1000',
                      '9' : '1001',
                      'a' : '1010',
                      'b' : '1011',
                      'c' : '1100',
                      'd' : '1101',
                      'e' : '1110',
                      'f' : '1111'}
    return ''.join([binary_mapping[hex_digit]
                    for hex_digit in hex(x)[2:]])
###



Here's what it looks like in action:

###
>>> for n in range(20):
...     print n, binary(n)
...
0 0000
1 0001
2 0010
3 0011
4 0100
5 0101
6 0110
7 0111
8 1000
9 1001
10 1010
11 1011
12 1100
13 1101
14 1110
15 1111
16 00010000
17 00010001
18 00010010
19 00010011
>>> binary(-42)
'11111111111111111111111111010110'
###


So that's yet another way to do binary()... *grin* It might seem like
cheating to take advantage of hex().  But then again, it's a common
programming technique to improve on a function that's almost does what we
want.



> Really? I'm surprised. I assume Guido doesn't do much with bitmaps or
> reading raw data from devices. The lack of a binary representation is a
> real pain. Not hard to code but why should I have to?!

I don't know... I feel that binary() is a bit too specialized to be put in
as a builtin.  But perhaps it might fit into a standard library module
somewhere?


Talk to you later!