本文介紹了獲取“位";Python中的浮點數?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在尋找與 Java 的 Float.floatToBits
等效的 Python.
I am looking for the Python equivalent of Java's Float.floatToBits
.
我發現了這個 Python:獲取 &操縱(作為整數)浮點數的位模式,但有人知道不那么復雜的方法嗎?
I found this Python: obtain & manipulate (as integers) bit patterns of floats but does anyone know of a less complicated way?
推薦答案
Alex Martelli 在該問題中給出的答案非常簡單——您可以將其簡化為:
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中的浮點數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!