Convert from C double wrapped to two hexadecimal strings

my first day with Python.

I like to filter the trace file generated by C. Each double of C is formatted in a file with two hexadecimal strings representing 32 bits of 64 doubles.

eg. 1234567890.3 (C double)
inside the file:

0xb4933333 0x41d26580 

How can I parse and combine it for further work with Python floating point?

Thanks in advance

+8
python string double floating-point hex
source share
2 answers

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 add to doubles, the above suggests a big-end machine. Also, I split 0x since the decode function decode not expect this.

edit: If you are 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 
+9
source share

Here is the IEEE standard for floating points and how to create it:

http://www.psc.edu/general/software/packages/ieee/ieee.php

0
source share

All Articles