Tiefseefisch
Tiefseefisch

Reputation: 21

How to import uint16_t array from binary data in Python?

I tried it with numpy:

numpy.fromfile(file_name, dtype=numpy.uint16)

but I get wrong numbers for example 0x3000 is converted to 48 which should be 12288.

Using struct.unpack didn't work:

struct.unpack("i" * ((len(bin_data.tobytes())) // 4), bin_data.tobytes())

because of this error:

Traceback (most recent call last):
  File "lc3.py", line 386, in <module>
    main()
  File "lc3.py", line 372, in main
    a = struct.unpack("i" * ((len(bin_data.tobytes())) // 4), bin_data.tobytes())
struct.error: unpack requires a buffer of 32 bytes

This is the binary:

00000000: 00110000 00000000 11100000 00000010 11110000 00100010  0...."
00000006: 11110000 00100101 00000000 01001000 00000000 01100101  .%.H.e
0000000c: 00000000 01101100 00000000 01101100 00000000 01101111  .l.l.o
00000012: 00000000 00101100 00000000 00100000 00000000 01010111  .,. .W
00000018: 00000000 01101111 00000000 01110010 00000000 01101100  .o.r.l
0000001e: 00000000 01100100 00000000 00000000                    .d..

This is the data I want:

0x3000,
0xE005,
0x2212,
0xF022,
0x127F,
0x03FD,
0xF025,
0x0048,
0x0065,
0x006C,
0x006C,
0x006F,
0x0020,
0x0057,
0x006F,
0x0072,
0x006C,
0x0064,
0x0021,
0x000A,
0x0000,
0x0005

This is the data I get:

['0x30', '0x2e0', '0x22f0', '0x25f0', '0x4800', '0x6500', '0x6c00', '0x6c00', '0x6f00', '0x2c00', '0x2000', '0x5700', '0x6f00', '0x7200', '0x6c00', '0x6400', '0x0']

Upvotes: 1

Views: 918

Answers (1)

Peter Gibson
Peter Gibson

Reputation: 19574

Sounds like you need to use a different byte ordering (note 'h' is the format specifier for 16bit ints).

>>> import struct
>>> struct.unpack('h', b'\x30\x00') # default byte ordering
(48,)
>>> struct.unpack('h', b'\x00\x30') # you get the right result if you swap the bytes in the file
(12288,)
>>> struct.unpack('<h', b'\x30\x00') # little endian
(48,)
>>> struct.unpack('>h', b'\x30\x00') # big endian <- this is likely what you want
(12288,)

In numpy you can use something like

>>> import numpy
>>> numpy.dtype('>h')
dtype('>i2')

Upvotes: 1

Related Questions