Skip to content
Advertisement

How to convert a binary (string) into a float value?

I want to convert a binary number into a float number. Here’s an example of a possibility:

>>> float(-0b1110)

gives me the correct output:

-14.0

Unfortunately, I am working with binary strings, i.e., I need something like float('-0b1110').
However, this doesn’t work:

>>> float('-0b1110')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): -0b1110

I tried to use binascii.a2b_qp(string[, header]) which converts a block of quoted-printable data back to binary and returns the binary data. But eventually, I get the same error:

>>> float(binascii.a2b_qp('-0b1110'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): -0b1110

I understand the cases where the output number is an integer but what if I want to obtain the number 12.546? What would the function call for the binary string look like then?

Advertisement

Answer

Another option is to do

from ast import literal_eval

float_str = "-0b101010101"
result = float(literal_eval(float_str))

Unlike the built-in “eval”, literal_eval is safe to be run even on user inputs, as it can only parse Python literals – and will not execute expressions, which means it will not call functions as well.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement