Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from a C double transferred in two hex strings

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

like image 640
Wolfgang R. Avatar asked Jul 15 '11 21:07

Wolfgang R.


People also ask

How do you convert hexadecimal to double?

X = hex2num( hexStr ) converts hexStr to the double-precision floating-point number that it represents. The input argument hexStr has up to 16 characters representing a number in its IEEE® format using hexadecimal digits.

Does atoi work for hex?

The atoi() and atol() functions convert a character string containing decimal integer constants, but the strtol() and strtoul() functions can convert a character string containing a integer constant in octal, decimal, hexadecimal, or a base specified by the base parameter.

How many form a hex can be converted into?

Hexadecimal is a base-16 number system. That means there are 16 possible digits used to represent numbers. 10 of the numerical values you're probably used to seeing in decimal numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9; those values still represent the same value you're used to.


1 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 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
like image 63
yan Avatar answered Sep 28 '22 07:09

yan