Converting an integer base 10 to a binary number
Robert Amesz
rcameszREMOVETHIS at dds.removethistoo.nl
Sat Mar 31 17:29:15 EST 2001
François Granger wrote:
>Peter Stöhr <peter.stoehr at fh-hof.de> wrote:
>
>> Hi out there,
>>
>> I know the int(x[,radix]) function that converts a string or a
>> number (for a give radix) to an integer. Is there a built-in
>> function that provides a conversion the other way round?
>> Something like
>> bin(32) = "10000"
>
>Not fully polished, but works
>
># python
>"""
>create the binary rep of an integer as a string of '0' & '1'
>20010302 v 1.0
>"""
>def toBin(x):
> a = ''
> y = x
> while x:
> x, y = x / 2, y % 2
> if y:
> a = '1' + a
> else:
> a = '0' + a
> y = x
> return a
>
>if __name__ == '__main__'
> l = [1, 2, 3, 4, 8, 16, 32, 64, 128, 255, 512, 1024, 2048, 4096,
>8192, 16384, 32768]
> for x in l:
> print toBin(x)
>
I'm afraid it doesn't work for x == 0, and you'll get into trouble when
x is a float. (Strong typing does have its merits.) Also, for binary
numbers we don't need the div-and-mod approach, a bitwise and (i.e. &)
will do. (Incidentally, although I'm not using it here, there's a
function called divmod() which is more efficient, presumably, than two
seperate operations.) That leaves us with:
def toBin(x):
x = int(x) # Just in case x is a float,
binstr = ''
while 1: # Can't use while x, because x may be 0 initially
if x & 1:
binstr = '1' + binstr
else:
binstr = '0' + binstr
x = x / 2
if not x:
return binstr
You can be even more concise (I don't know about the efficiency,
though) by replacing the if/else statement by:
binstr = string.digits[x & 1] + binstr
or:
binstr = ('0', '1')[x & 1] + binstr
Robert Amesz
More information about the Python-list
mailing list