How to convert a string representing a binary fraction to a number in Python

binary, fractions, python

Solution

The following is a shorter way to express the same algorithm:

def parse_bin(s):
    return int(s[1:], 2) / 2.**(len(s) - 1)

It assumes that the string starts with the dot. If you want something more general, the following will handle both the integer and the fractional parts:

def parse_bin(s):
    t = s.split('.')
    return int(t[0], 2) + int(t[1], 2) / 2.**len(t[1])

For example:

In [56]: parse_bin('10.11')
Out[56]: 2.75

Problem

Let us suppose that we have a string representing a binary fraction such as: ``` ".1" ``` As a decimal number this is 0.5. Is there a standard way in Python to go from such strings to a number type (whether it is binary or decimal is not strictly important). For an integer, the solution is straightforward: ``` int("101", 2) >>>5 ``` int() takes an optional second argument to provide the base, but float() does not. I am looking for something functionally equivalent (I think) to this: ``` def frac_bin_str_to_float(num): """Assuming num to be a string representing the fractional part of a binary number with no integer part, return num as a float.""" result = 0 ex = 2.0 for c in num: if c == '1': result += 1/ex ex *= 2 return result ``` I think that does what I want, although I may well have missed some edge cases. Is there a built-in or standard method of doing this in Python?

Original source