Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 265
Tom Scrace Avatar asked Dec 01 '12 19:12

Tom Scrace


People also ask

How do you convert a fraction to a binary number?

To convert fraction to binary, start with the fraction in question and multiply it by 2 keeping notice of the resulting integer and fractional part. Continue multiplying by 2 until you get a resulting fractional part equal to zero. Then just write out the integer parts from the results of each multiplication.

How do you convert binary to numbers in Python?

In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.

What method is used to represent fractions in binary numbers in Python?

You use the Binary fractions package. It has many more helper functions to manipulate binary strings such as: shift, add, fill, to_exponential, invert...

How to convert a binary string to an integer in Python?

First of all, let us convert a binary string into an integer using the int () function in Python. the following is a simple Python program to convert a binary string into an integer: number= input ('Enter a Binary number:') dec_number= int (number, 2) print ('The decimal conversion is:', dec_number) print (type (dec_number))

Is there a standard way to convert strings to numbers in Python?

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

How to convert a binary to an octal in Python?

In Python, If you want to convert a binary number into an octal, you have to convert the binary into a decimal first, and then convert this decimal number into an octal number. In the above program, we have used the for loop to convert a binary into decimal. Then we used the while loop to convert that decimal into an octal.

How to convert binary string literals to floats in Python?

For example, we can convert the following binary string to a base 10 integer using the base parameter: The same can be done for any other base, like hexadecimal (base 16): Converting string literals to floats is done via the float () function:


2 Answers

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
like image 82
NPE Avatar answered Oct 23 '22 20:10

NPE


It is reasonable to suppress the point instead of splitting on it, as follows. This bin2float function (unlike parse_bin in previous answer) correctly deals with inputs without points (except for returning an integer instead of a float in that case).

For example, the invocations bin2float('101101'), bin2float('.11101'), andbin2float('101101.11101')` return 45, 0.90625, 45.90625 respectively.

def bin2float (b):
    s, f = b.find('.')+1, int(b.replace('.',''), 2)
    return f/2.**(len(b)-s) if s else f
like image 3
James Waldby - jwpat7 Avatar answered Oct 23 '22 19:10

James Waldby - jwpat7