使用 PYTHON,您(首选 easiest/best/pythonic 方式)如何查看 64 位浮点数的内部表示?
With PYTHON, how can the you (easiest/best/pythonic way preferred) see the INTERNAL REPRESENTATION OF A 64 BIT FLOAT?
在 C 中,我可以轻松地(最难的部分是 lX 与 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
正如评论中提到的——这之前已经解决了,我的验证复制在这里 convenience/posterity:
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'
在 C 中,我可以轻松地(最难的部分是 lX 与 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
正如评论中提到的——这之前已经解决了,我的验证复制在这里 convenience/posterity:
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'