将float的位重新解释为int在Python中。

huangapple go评论64阅读模式
英文:

How to reinterpret bits of float as int in python

问题

Here's the translated content:

我必须编写代码以打印浮点数的位(十六进制形式)。对于C++,我首先想到的是
std::cout << std::hex << *reinterpret_cast<uint32_t*>(&x);
其中x是存储原始数字的浮点变量。

然而,当我尝试在Python中解决同样的问题时,我简直想不出一种Python的方式来解决它(不允许使用非内置库)。我最好的尝试导致了类似于这样的东西:

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版本是否引入了对这种情况有用的东西?

英文:

I had to write code that printed out bits of floating point number (in hexadecimal). For C++, the first thing that came to mind was
std::cout << std::hex << *reinterpret_cast<uint32_t*>(&x);
where x is a floating point variable that stores the original number.

However, when I tried the same problem in python, I just couldn't come up with a python-ish way to solve it (using not built-in libraries is not allowed). My best attempts lead to something like this:

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:])

which is basically C code.

So, is there more "python" way to do this? Did recent python versions introduce something that could be useful for this case?

答案1

得分: 0

Your implementation is inaccurate because float in CPython implementation is a double precision floating-point type (c++ double) so its size is 64 bit. You have to use c_uint64 and c_double for best results.

You can use the struct module to pack float to Python bytes object and then unpack it to integer value:

import struct
float_to_hex = lambda f: hex(struct.unpack('@Q', struct.pack('@d', f))[0])
print(float_to_hex(123.45)) # Output: 0x405edccccccccccd

"Python" way: you can just use the float.hex() method, but the result will be different:

print(123.45.hex()) # Output: 0x1.edccccccccccdp+6
英文:

Firstly, your implementation is inaccurate because float in CPython implementation is a double precision floating-point type (c++ double) so it's size is 64 bit. You have to use c_uint64 and c_double for best results

You can use the struct module to pack float to Python bytes object and then unpack it to integer value:

import struct
float_to_hex = lambda f: hex(struct.unpack('@Q', struct.pack('@d', f))[0])
print(float_to_hex(123.45)) # Output: 0x405edccccccccccd

"Python" way: you can just use the float.hex() method but the result will be different:

print(123.45.hex()) # Output: 0x1.edccccccccccdp+6

huangapple
  • 本文由 发表于 2023年5月14日 23:28:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76248276.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定