[Tutor] Bits operations

Magnus Lyckå magnus@thinkware.se
Fri Jul 11 20:52:01 2003


At 22:39 2003-07-11 +0100, 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! :)
>
>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?!

He's not an engineer you know. He is basically a mathematician
as far as I understand, and that makes him a bit...different
I guess. ;)

(BTW, I just noticed that he quit working for Zope Corp and is
now with Elemental Security, founded by Dan Farmer, the guy who
wrote the security checker Satan a number of years ago. It seems
Guido prefers to live in California...)

>And watching a single bit toggling in binary is much easier
>than watching a hex or octal digit changing and mentally
>working out which input line triggered it!

It's no huge thing. Binary string to integer value is handled
by int(x,2), e.g.

 >>> int('10100101',2)
165

I can agree that is would be neat if I could simply type

 >>> 0b10100101
165

but I can live without that...

Going the other way around, it would be nice with a builtin
companion to hex and oct, as well as a "%b" to complement
"%x%o%i"... But "%s" % b(n) with b() defined as below does
the job I guess... at least for non-negative numbers.

def b(i, l=0):
     s = []
     while i:
         s.append(str(i%2))
         i >>= 1
     s.extend(['0']*(l-len(s)))
     s.reverse()
     return "".join(s)


--
Magnus Lycka (It's really Lyckå), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language