1

I have some 32bits binary numbers. I want to convert them to decimal form. does exist any built-in function or general solution for this task? The following image shows an example.

enter image description here.

MH.AI.eAgLe
  • 592
  • 1
  • 6
  • 22
  • `np.frombuffer` might work. Give an example or two. – hpaulj Apr 23 '20 at 04:26
  • You presumably want to convert from the `int` value to a `float` in a custom way (interpreting the bits according to that diagram), and then *display* the float in decimal. – Karl Knechtel Apr 23 '20 at 04:53
  • no according to the above image I have some 32 bits numbers. for example, I have such a number: "11000011011110001100000000000000" which its conversion is -248.75 – MH.AI.eAgLe Apr 23 '20 at 04:57
  • Does this answer your question? [How to convert 32-bit binary to float](https://stackoverflow.com/questions/33483846/how-to-convert-32-bit-binary-to-float) – Jongware Apr 23 '20 at 06:38

2 Answers2

2

You can use struct module.

import struct
def bin_to_float(binary):
    return struct.unpack('!f',struct.pack('!I', int(binary, 2)))[0]

print(bin_to_float("11000011011110001100000000000000"))
##Output -248.75
Prudhvi
  • 1,095
  • 1
  • 7
  • 18
  • Thanks a lot, I don't know why I'm getting nan with this :bin_to_float("11111111111101111010111000010100") – MH.AI.eAgLe Apr 23 '20 at 04:37
  • I am getting `nan` when I convert Online also - https://www.binaryconvert.com/convert_float.html – Prudhvi Apr 23 '20 at 04:46
  • 1
    The exponent here has all `1` bits, and [according to the specification](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) this is reserved for special values. So a `nan` is not surprising. – Karl Knechtel Apr 23 '20 at 04:56
0

Working from:

What's the correct way to convert bytes to a hex string in Python 3?

In [54]: bytes.fromhex('c378c000')                                                                     
Out[54]: b'\xc3x\xc0\x00'
In [55]: np.frombuffer(bytes.fromhex('c378c000'), '>f4')                                               
Out[55]: array([-248.75], dtype=float32)

np.float32 is IEEE 754 format.

hpaulj
  • 221,503
  • 14
  • 230
  • 353