-1

I have the following 8 byte string that forms part of a binary file

b = b'?\xf0\x00\x00\x00\x00\x00\x00'

and I want to convert it to a floating point number (which should be equal to 7.371791007870371e+05). None of the approaches that I've tried so far have worked:

  • literal_eval

    from ast import literal_eval literal_eval(b) ValueError: malformed node or string: b'?\xf0\x00\x00\x00\x00\x00\x00'

  • following @martineau's answer in this post: How to convert a binary (string) into a float value?

    ValueError: invalid literal for int() with base 2: b'?\xf0\x00\x00\x00\x00\x00\x00'

In both cases the errors raised suggest that the string 'b' is invalid, but I don't see how this is possible as it's read straight from the binary file.

Dai
  • 345
  • 3
  • 12
  • 4
    Your string `b` is likely invalid (it's all null bytes except the first 2) - at the very least, that string does not represent the float 7.371791007870371e+05. – wim Apr 30 '18 at 20:28
  • 2
    btw 8 bytes float for the number in your question should look like `b'\xc8[\x9a36\x7f&A'`. – wim Apr 30 '18 at 20:30
  • 2
    `struct.unpack('d', b'\xc8[\x9a36\x7f&A')[0]` should work then. Output is `737179.100787037` – TwistedSim Apr 30 '18 at 20:30
  • `float` takes 4 bytes. Which of your 8 bytes you want to convert? – CristiFati Apr 30 '18 at 20:35

1 Answers1

2

This should unpack the bytes to a double (8 bytes, not a float which is 4 bytes). Note that I use the value from @wim.

import struct
print(struct.unpack('d', b'\xc8[\x9a36\x7f&A')[0])
TwistedSim
  • 1,960
  • 9
  • 23