[Tutor] Binary
Kalle Svensson
kalle@gnupung.net
Sat, 12 May 2001 13:18:59 +0200
Sez Sheila King:
> On Fri, 11 May 2001 22:10:42 -0400 (EDT), "Michael P. Reilly"
> <arcege@dsl092-074-184.bos1.dsl.speakeasy.net> wrote about Re: [Tutor] Binary:
>
> :def bin(n):
> : """Return a bit string representing the number, right-justified."""
> : s = ''
> : while n:
> : if n & 01:
> : s = '1' + s
> : else:
> : s = '0' + s
> : n = n >> 1
> : return s
>
> OK, I tried this out, and it works, apparently.
> But I don't understand the code.
>
> What does this line do?
>
> if n & 01:
n & 01 is the bitwise and of n and 1. This is 1 if the least significant
bit of n is 1, else 0.
> and what about this line?
>
> n = n >> 1
All the bits in n are shifted one step to the right:
>>> bin(13)
'1101'
>>> bin(13 >> 1)
'110'
>>> bin(13 >> 2)
'11'
>>> bin(13 >> 3)
'1'
>>> bin(13 >> 4)
''
> I thought, for a minute, someone was using C or C++ to "extend" Python, until I
> looked more carefully.
You could replace
if n & 01:
with
if n % 2:
and
n = n >> 1
with
n = n / 2
but that would be slower.
Peace,
Kalle
--
Email: kalle@gnupung.net | You can tune a filesystem, but you
Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8)
PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD
[ Not signed due to lossage. Blame Microsoft Outlook Express. ]