Decimal to binary Half-Precision IEEE 754 in Python

烈酒焚心 提交于 2019-12-10 19:17:21

问题


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"


回答1:


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

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



回答2:


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()


来源:https://stackoverflow.com/questions/33451800/decimal-to-binary-half-precision-ieee-754-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!