سؤال

I'm trying to unpack a binary string sent via Javascript's FileReader readAsBinaryString method in my python app. It seems I could use the struct module for this. I'm unsure what to provide as as the format for the unpack exactly.

Can someone confirm this is the right approach, and if so, what format I should specify?

According to the JS documentation:

The result will contain the file's data as a binary string. Every byte is represented by an integer in the range [0..255].

هل كانت مفيدة؟

المحلول

It sounds as if you just have an ordinary string (or bytes object in Python 3), so I'm not sure what you need to unpack.

One method of accessing the byte data is to use a bytearray; this lets you index the byte data easily:

>>> your_data = b'\x00\x12abc'
>>> b = bytearray(your_data)
>>> b[0]
0
>>> b[1]
18

If you have it as a string and don't want to use a bytearray (which need Python 2.6 or later) then use ord to convert the character to an integer.

>>> ord(your_data[1])
18

If your binary data has a particular interpretation in terms of groups of bytes representing integers or floats with particular endianness then the struct module is certainly your friend, but you don't need it just to examine the byte data.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top