简体   繁体   English

Python 中的十进制到二进制半精度 IEEE 754

[英]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我只能够十进制转换成二进制单精度IEEE754,使用struct.pack模块,或做使用相反(float16或FLOAT32) numpy.frombuffer

Is it possible to convert a decimal to a binary half precision floating point, using Numpy?是否可以使用 Numpy 将十进制转换为二进制半精度浮点数?

I need to print the result of the conversion, so if I type "117.0" , it should print "0101011101010000"我需要打印转换的结果,所以如果我输入"117.0" ,它应该打印"0101011101010000"

if I type "117.0", it should print "0101011101010000"如果我输入“117.0”,它应该打印“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. .view('H')float16值占用的内存重新解释为无符号整数。

Mark Dickinson建议的float16方法必须跟在tostring()方法之后才能获得所需的二进制表示:

data = numpy.float16(2.3).tostring()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM