另见How to convert a float into hex为双至十六进制
import struct
def double_to_hex(f):
return hex(struct.unpack('<Q', struct.pack('<d', f))[0])
doubleAsHex = double_to_hex(2.1)
print("doubleAsHex (correct):", doubleAsHex)
doubleAsBytes = bytearray.fromhex(doubleAsHex.replace('0x',''))
print("doubleAsBytes (missing first byte):", doubleAsBytes)
输出:
doubleAsHex (correct): 0x4000cccccccccccd
doubleAsBytes (missing first byte): bytearray(b'@\x00\xcc\xcc\xcc\xcc\xcc\xcd')
什么是省略字节的原因?
如您所示:
doubleAsHex (correct): 0x4000cccccccccccd
doubleAsBytes (missing first byte): bytearray(b'@\x00\xcc\xcc\xcc\xcc\xcc\xcd')
如果我们打破字节数组,你将得到以下内容:
[0] => @ # First Byte
[1] => 00
[2] => cc
[3] => cc
[4] => cc
[5] => cc
[6] => cc
[7] => cd
但是会发生的是打印功能是采用十六进制40,其中ascii是@,它与其他的不一样,因为有数字和十六进制你可以有unil F