根据@Hannes Karppila的回答,这里有两个函数,它们以二进制和十六进制格式显示任意数字的机器表示。它使用与答案基本相同的逻辑,但用零填充输出以显示每个字节的“正确”长度。
import ctypes
import decimal
def print_as_octave_bit_hex(x):
'''
This function prints the binary representation as it would
be printed using the format 'bit' and 'hex' in octave
'''
asdouble = ctypes.c_double(x)
xpointer = ctypes.addressof(asdouble)
xdata = ctypes.string_at(xpointer, 8)
xbin= [(bin(i)[2:].zfill(8)) for i in xdata[-1::-1]]
print(x, "=", x.hex(), "=", decimal.Decimal(x))
print("representation in format 'bit' and 'hex' of octave")
print("with spaces separating each byte")
print(" ".join([i.zfill(8) for i in xbin]), "=",
" ".join([hex(int(i,2))[2:].zfill(2) for i in xbin]))
print("without spaces separating the bytes")
print("".join([i.zfill(8) for i in xbin]), "=",
"".join([hex(int(i,2))[2:].zfill(2) for i in xbin]))
def print_as_octave_native_bit_hex(x):
'''
This function prints the binary representation as it would
be printed using the format 'native-bit' and 'native-hex' in octave
'''
asdouble = ctypes.c_double(x)
xpointer = ctypes.addressof(asdouble)
xdata = ctypes.string_at(xpointer, 8)
xbin = [(bin(i)[2:].zfill(8)) for i in xdata]
print(x, "=", x.hex(), "=", decimal.Decimal(x))
print("representation in format 'native-bit' and 'native-hex' of octave")
print("with spaces separating each byte")
print(" ".join([(i.zfill(8))[-1::-1] for i in xbin]), "=",
" ".join([hex(int(i,2))[2:].zfill(2) for i in xbin]))
print("without spaces separating the bytes")
print("".join([(i.zfill(8))[-1::-1] for i in xbin]), "=",
"".join([hex(int(i,2))[2:].zfill(2) for i in xbin]))
x=1.1+2.2
print_as_octave_bit_hex(x)
print(" ")
print_as_octave_native_bit_hex(x)
3.3000000000000003 = 0x1.a666666666667p+1 = 3.300000000000000266453525910037569701671600341796875
representation in format 'bit' and 'hex' of octave
with spaces separating each byte
01000000 00001010 01100110 01100110 01100110 01100110 01100110 01100111 = 40 0a 66 66 66 66 66 67
without spaces separating the bytes
0100000000001010011001100110011001100110011001100110011001100111 = 400a666666666667
3.3000000000000003 = 0x1.a666666666667p+1 = 3.300000000000000266453525910037569701671600341796875
representation in format 'native-bit' and 'native-hex' of octave
with spaces separating each byte
11100110 01100110 01100110 01100110 01100110 01100110 01010000 00000010 = 67 66 66 66 66 66 0a 40
without spaces separating the bytes
1110011001100110011001100110011001100110011001100101000000000010 = 6766666666660a40
我怀疑它; Python不鼓励知道或关心事物在内存中的存储位置和方式。你想用它做什么? – jonrsharpe
相关:[Python中的float的二进制表示形式(位不是十六进制)](http://stackoverflow.com/q/16444726/953482)。这只是为了漂浮。 – Kevin
@凯文感谢您的链接,但它不是我所期待的。 @jonsharpe我发现它非常方便,在教授数值分析类时,使用八度中的“格式位”来解释浮点表示法,归一化与非规格化浮点数等。但是我想开始使用python作为类,因此查询。 –