How to convert base 10 to base 2?
Jean-Michel Pichavant
jeanmichel at sequans.com
Mon Aug 20 10:52:42 EDT 2012
gianpycea at gmail.com wrote:
> On Monday, August 20, 2012 9:50:53 AM UTC+2, (unknown) wrote:
>
>> Hi,
>>
>> as you can argue from the subject, i'm really,really new to python.
>>
>> What is the best way to achieve that with python? Because the syntax int('30',2) doesn't seem to work!
>>
>
> Thank you all for the big help!
> @Mark Lawrence
> Yes, you're definetely right: i should have posted my OS and the version but being a very rough question on syntax i thought it didn't really matter.
> I've quite a good general programming experience. I know Java,Visual Basic.NET,Pascal and Mathematica.
>
note that the builtin bin function is not available with python ver < 2.6
def Denary2Binary(n):
'''convert denary integer n to binary string bStr'''
bStr = ''
if n < 0: raise ValueError, "must be a positive integer"
if n == 0: return '0'
while n > 0:
bStr = str(n % 2) + bStr
n = n >> 1
return bStr
JM
(not my function but I can't remember who I stole from)
More information about the Python-list
mailing list