使用PYTHON,您(最简单/最好/PYTHON方式首选)如何看到64位浮点的内部表示?

2024-05-23 13:35:26 发布

您现在位置:Python中文网/ 问答频道 /正文

在C语言中,我可以很容易地(最难的部分是lX vs X)确定64位浮点的内部表示形式,这很容易理解和纠正——我如何在PYTHON中做到这一点(2个首选)?:

Mac_3.2.57$cat f.c
#include <stdio.h>
main(void){
    union A64bFloatOrLong{
        double F;
        long L;}a64bFloatOrLong;
    a64bFloatOrLong.F=1.0;
    printf("0x%016.16lX\n",a64bFloatOrLong.L);}
Mac_3.2.57$cc f.c
f.c:2:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
main(void){
^
1 warning generated.
Mac_3.2.57$./a.out
0x3FF0000000000000

Tags: includemainmac形式catint浮点vs
1条回答
网友
1楼 · 发布于 2024-05-23 13:35:26

如评论中所述,这是之前解决的问题,为了方便/子孙后代,我在此处复制了我的验证:

Mac_3.2.57$python
Python 2.7.10 (default, Jul 15 2017, 17:16:57) 
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> def double_to_hex(f):
...     return hex(struct.unpack('<Q', struct.pack('<d', f))[0])
... 
>>> double_to_hex(17.5)   # Output: '0x4031800000000000L'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in double_to_hex
NameError: global name 'struct' is not defined
>>> import struct
>>> double_to_hex(17.5)   # Output: '0x4031800000000000L'
'0x4031800000000000'
>>> double_to_hex(1.0)   # Output: '0x4031800000000000L'
'0x3ff0000000000000'

相关问题 更多 >