Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal to binary Half-Precision IEEE 754 in Python

I was only able to convert a decimal into a binary single-precision IEEE754, using the struct.pack module, or do the opposite (float16 or float32) using numpy.frombuffer

Is it possible to convert a decimal to a binary half precision floating point, using Numpy?

I need to print the result of the conversion, so if I type "117.0", it should print "0101011101010000"

like image 693
Kaio Avatar asked Dec 06 '22 19:12

Kaio


2 Answers

if I type "117.0", it should print "0101011101010000"

>>> import numpy as np
>>> bin(np.float16(117.0).view('H'))[2:].zfill(16)
'0101011101010000'

.view('H') reinterprets the memory occupied by the float16 value as an unsigned integer.

like image 121
jfs Avatar answered Dec 17 '22 09:12

jfs


The float16 method suggested by Mark Dickinson has to be followed by the tostring() method to obtain the required binary representation:

data = numpy.float16(2.3).tostring()
like image 21
dlask Avatar answered Dec 17 '22 10:12

dlask