Binary Decimals in Python

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Tue Mar 30 13:05:14 EDT 2010


On Tue, 30 Mar 2010 08:28:50 -0700, Patrick Maupin wrote:

> On Mar 30, 10:13 am, aditya <bluemangrou... at gmail.com> wrote:
>> To get the decimal representation of a binary number, I can just do
>> this:
>>
>> int('11',2) # returns 3
>>
>> But decimal binary numbers throw a ValueError:
>>
>> int('1.1',2) # should return 1.5, throws error instead.
>>
>> Is this by design? It seems to me that this is not the correct
>> behavior.
>>
>> - Aditya
> 
> So, why should int('1.1', 2) throw an error when int('1.1') doesn't?


>>> int('1.1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1.1'


int('1.1', 2) shouldn't return 1.5 because 1.5 isn't an integer.


The obvious question is, why doesn't float('1.1', 2) work? The answer is 
that Python doesn't support floats in any base except 10. It's not 
something needed very often, and it's harder to get right than it might 
seem.



-- 
Steven



More information about the Python-list mailing list