0

see also How to convert a float into hex for double to 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)

output:

doubleAsHex (correct): 0x4000cccccccccccd
doubleAsBytes (missing first byte): bytearray(b'@\x00\xcc\xcc\xcc\xcc\xcc\xcd')

Whats the reason for the omitted byte?

user1323995
  • 1,286
  • 1
  • 10
  • 16

1 Answers1

0

As you have already shown:

doubleAsHex (correct): 0x4000cccccccccccd
doubleAsBytes (missing first byte): bytearray(b'@\x00\xcc\xcc\xcc\xcc\xcc\xcd')

if we break the byte array you are going to have the following:

[0] => @  # First Byte 
[1] => 00
[2] => cc
[3] => cc
[4] => cc
[5] => cc
[6] => cc
[7] => cd

But what happens is that the print function is taking the hex 40 which in ascii is @, it doesn't makes the same with the others because there are numbers and in hexadecimal you can have unil F

Kevin Cando
  • 170
  • 7