2
import struct
fileContent = b'@X\xa6fffff\x00\x00\x03\xe8\x01'
d = struct.unpack('d', fileContent[:8])
print(d)  # prints 98.6

I tried to use the struct module's unpack function but it returns large number 1.9035985675205313e+185 instead of 98.6 which it is supposed to do

2
  • Does this answer your question? How to convert a binary (string) into a float value? Commented Mar 4, 2023 at 14:20
  • 1
    struct.pack('d', 98.6) gives me b'fffff\xa6X@'. System byte order on the file io maybe? No, that wouldn't reverse all the bytes. Commented Mar 4, 2023 at 14:22

1 Answer 1

1

Listing [Python.Docs]: struct - Interpret strings as packed binary data.

If the expected value out of (the beginning of) this contents is 98.6, @KennyOstrom's comment is correct, it's the byte order (buffer is encoded using big endian, while the default (for Intel / AMD processors - pc064) is little endian)).
I prepared a small example (used unpack_from as it offers more flexibility).

code00.py:

#!/usr/bin/env python

import struct
import sys


def main(*argv):
    buf = b"@X\xa6fffff\x00\x00\x03\xe8\x01"

    for fmt, desc in (
        ("d", "default"),
        ("<d", "little"),
        (">d", "big"),
        ("@d", "native"),
    ):
        print("{:s}: {:.3f}".format(desc, struct.unpack_from(fmt, buf, offset=0)[0]))


if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.\n")
    sys.exit(rc)

Output:

(py_pc064_03.10_test1_pycoral) [cfati@cfati-5510-0:/mnt/e/Work/Dev/StackExchange/StackOverflow/q075636237]> python code00.py 
Python 3.10.7 (main, Sep  7 2022, 15:22:19) [GCC 9.4.0] 064bit on linux

default: 190359856752053127312676546256227168338472159449511832371070549056562920816076745060533362243045799043492106313588416013686785864748509740443321063342671014033379311055519472484045815808.000
little: 190359856752053127312676546256227168338472159449511832371070549056562920816076745060533362243045799043492106313588416013686785864748509740443321063342671014033379311055519472484045815808.000
big: 98.600
native: 190359856752053127312676546256227168338472159449511832371070549056562920816076745060533362243045799043492106313588416013686785864748509740443321063342671014033379311055519472484045815808.000

Done.

Might also be useful to check:

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much everyone! Yeshwin Verma The Programmer, Kenny Ostrom, and especially @CristiFati!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.