nurabha
nurabha

Reputation: 1212

Struct unpack endianness issue: bad char in struct format

I am reading a binary file into a stream of 4-byte unsigned integers.

if filename:
    with open(filename, mode='rb') as file:
        fileData = file.read()
        u32Data = struct.unpack('I' * (len(fileData )//4), fileData )

The default endianness on my machine is little-endian. I changed the endianness to big-endian in last line of code above:

u32Data = struct.unpack('>I' * (len(fileData )//4), fileData )

However I get following error when I change the last line from little to big endian:

struct.error: bad char in struct format

How to fix this ?

Upvotes: 0

Views: 246

Answers (1)

tkausl
tkausl

Reputation: 14279

Your format string ends up as '>I>I>I>I>I>I...' which is invalid, > is only allowed as very first letter in your format string. Use

u32Data = struct.unpack('>' + ('I' * (len(fileData )//4)), fileData )

Upvotes: 2

Related Questions