如何在 python 中将 float 位重新解释为 int

问题描述 投票:0回答:0

我必须编写代码来打印出浮点数位(十六进制)。对于C++,首先想到的是

std::cout << std::hex << *reinterpret_cast<uint32_t*>(&x);
其中 x 是存储原始数字的浮点变量。

但是,当我在 python 中尝试同样的问题时,我就是想不出一个 python-ish 的方法来解决它(不允许使用非内置库)。我最好的尝试导致了这样的事情:

from ctypes import Union, c_uint32, c_float

class conversion(Union):
    _fields_ = [("int", c_uint32),
                ("float", c_float)]

v = conversion()
v.float = float(input())
print(hex(v.int)[2:])

这基本上是 C 代码。

那么,有没有更多的“蟒蛇”方式来做到这一点?最近的 python 版本是否引入了对这种情况有用的东西?

python floating-point integer bit
© www.soinside.com 2019 - 2024. All rights reserved.