5xum
5xum

Reputation: 5545

BitConverter.DoubleToInt64Bits equivalent in python

I figure my best way of really getting a feeling about double precision numbers is to play around with them a bit, and one of the things I want to do is to look at their (almost) binary representation. For this, in C#, the function BitConverter.DoubleToInt64Bits is very useful, as it (after converting into hexadecimal) gives me a look at what the "real" nature of the floating point number is.

The problem is that I don't seem to be able to find the equivalent function in Python, is there a way to do the same things as BitConverter.DoubleToInt64Bits in a python function?

Thank you.


EDIT:

An answer bellow suggested usinginascii.hexlify(struct.pack('d', 123.456) to convert the double into a hexadecimal representation, but I am still getting strange results.

For example,

inascii.hexlify(struct.pack('d', 123.456))

does indeed return '77be9f1a2fdd5e40' but if I run the code that should be equivalent in C#, i.e.

BitConverter.DoubleToInt64Bits(123.456).ToString("X")

I get a completely different number: "405EDD2F1A9FBE77". Where have I made my mistake?

Upvotes: 1

Views: 1225

Answers (1)

falsetru
falsetru

Reputation: 369274

How about using struct.pack and binascii.hexlify?

>>> import binascii
>>> import struct
>>> struct.pack('d', 0.0)
'\x00\x00\x00\x00\x00\x00\x00\x00'
>>> binascii.hexlify(struct.pack('d', 0.0))
'0000000000000000'
>>> binascii.hexlify(struct.pack('d', 1.0))
'000000000000f03f'
>>> binascii.hexlify(struct.pack('d', 123.456))
'77be9f1a2fdd5e40'

struct format specify d represent double c type (8 bytes = 64 bits). For other format, see Format characters.

UPDATE

By specifying @, =, <, >, ! as the first character of the format, you can indicate byte order. (Byte Order, Size, and Alignment)

>>> binascii.hexlify(struct.pack('<d', 123.456)) # little-enddian
'77be9f1a2fdd5e40'
>>> binascii.hexlify(struct.pack('>d', 123.456)) # big-endian
'405edd2f1a9fbe77'

Upvotes: 3

Related Questions