英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论