获取“比特”在Python中的浮点数? [英] Get the "bits" of a float in Python?

查看:230
本文介绍了获取“比特”在Python中的浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找Java的 Float.floatToBits 的Python等价物。



我发现这个,但没有人知道一个不太复杂的方式吗? 解决方案

答案Alex Martelli在这个问题上给出的内容非常简单 - 你可以把它简化为:

 >>> import struct 
>>>
>>>
>>> def floatToBits(f):
... s = struct.pack('> f',f)
... return struct.unpack('> l',s)[0]
...
...
>>> floatToBits(173.3125)
1127043072
>>>十六进制(_)
'0x432d5000'

一旦你把它作为一个整数执行你需要的任何其他操作。



您可以将操作顺序颠倒过来:

 >>> def bitsToFloat(b):
... s = struct.pack('> l',b)
... return struct.unpack('> f',s)[0]

>>> bitsToFloat(0x432d5000)
173.3125


I am looking for the Python equivalent of Java's Float.floatToBits.

I found this Python: obtain & manipulate (as integers) bit patterns of floats but does anyone know of a less complicated way?

解决方案

The answer that Alex Martelli gives in that question is really pretty simple -- you can reduce it to:

>>> import struct
>>> 
>>> 
>>> def floatToBits(f):
...     s = struct.pack('>f', f)
...     return struct.unpack('>l', s)[0]
...     
... 
>>> floatToBits(173.3125)
1127043072
>>> hex(_)
'0x432d5000'

Once you have it as an integer, you can perform any other manipulations you need to.

You can reverse the order of operations to round-trip:

>>> def bitsToFloat(b):
...     s = struct.pack('>l', b)
...     return struct.unpack('>f', s)[0]

>>> bitsToFloat(0x432d5000)
173.3125

这篇关于获取“比特”在Python中的浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆