I have a binary float like '10.1' and want to convert it to a decimal float. Then I want to do some operations on it and convert it back to a binary float. Are there builtins in python 2 to do this? If not, what is the shortest (in bytes) way to do this?
Asked
Active
Viewed 615 times
-3
-
1Can you give an example? What does the binary float "10.1" look like as a decimal float? What operations will you do on it? And what will it look like when you convert it back? – Kevin Jan 04 '16 at 19:44
-
@Kevin it would look like "2.1". The operations done is just an eval(). There is a string with binary floats, each are converted to base 10 float, then the string is evaluated, and the result is converted back to binary float. – TanMath Jan 04 '16 at 19:46
-
Is 2.1 the actual number it would be converted to, or is that just an example of what it would "look" like? – Kevin Jan 04 '16 at 19:50
-
1Check [this out](http://rosettacode.org/wiki/Decimal_floating_point_number_to_binary#Python) – Bob Dylan Jan 04 '16 at 20:07
-
1Really "2.1"? Or did you mean "2.5"? – Mark Dickinson Jan 04 '16 at 21:12
-
@MarkDickinson sorry, you are correct...That is what I meant – TanMath Jan 04 '16 at 21:13
-
@BobDylan so there isn't a builtin way of doing this? – TanMath Jan 04 '16 at 22:47
-
[You can do this with the `struct` package](http://stackoverflow.com/a/16444778/5221082), but you're just doing glorified string manipulation. The underlying data structure is still not what you're after. – Bob Dylan Jan 05 '16 at 15:02
-
Are you actually interested in the shortest in bytes solution? Because that'd be code golf and it might result in something unintuitive and unreadable. I think you meant something along the lines *not verbose, but short, readable and efficient*. – Reti43 Jan 06 '16 at 11:05
-
@Reti43 yes, and having done code golf for several months I get the gist of it. It would be fine if the answerer includes an ungolfed version for other readers perhaps. – TanMath Jan 06 '16 at 18:58
1 Answers
2
There's no built-in way to do this for binary (though there is from hexadecimal). The easiest way would be to strip out the .
, parse as an integer, and scale appropriately:
import math
x = "10.1"
p = len(x) - x.index(".") - 1
i = int(x.replace(".",""),2)
math.ldexp(i,-p)
This assumes your string consists of nothing but 0
s, 1
s and a single .
(i.e. no whitespace or exponent).

Simon Byrne
- 7,694
- 1
- 26
- 50