Reputation: 333
my very first day with Python.
I like to filter on a trace file generated by C. Each double from C is formatted in the file by two hex strings representing 32 bit of the 64 double.
e.g. 1234567890.3 (C double)
inside file:
0xb4933333
0x41d26580
How can I parse and combine it to further work with a Python float?
Thanks in advance
Upvotes: 8
Views: 518
Reputation: 20992
You can use struct
, using the 'd' modifier for 'double':
>>> import struct
>>> num1 = '0xb4933333'
>>> num2 = '0x41d26580'
>>> struct.unpack('!d', (num2[2:]+num1[2:]).decode('hex'))[0]
1234567890.3
Be careful what order you append the doubles in, the above assumes a big-endian machine. Also, I stripped 0x
as the decode
function doesn't expect it.
edit: If you're using Python 3, you need to use bytes.fromhex
instead of ''.decode('hex')
.
Just to give an alternative (the above is a very nice solution):
>>> import struct
>>> num1 = '0xb4933333'
>>> num2 = '0x41d26580'
>>> low_word = int(num1, 16)
>>> high_word = int(num2, 16)
>>> representation = struct.pack('>II', high_word, low_word)
>>> result = struct.unpack('>d', representation)
>>> result[0]
1234567890.3
Upvotes: 9
Reputation: 129
Here is a the IEEE standard for floating points and how it is created:
http://www.psc.edu/general/software/packages/ieee/ieee.php
Upvotes: 0