NewCoder
NewCoder

Reputation: 91

Struct.error: unpack requires a buffer of 16 bytes

I have binary file which is this format (b'A\xd9\xa5\x1ab\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x0b\xda\xa5\x1ab\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\xcd\xdb\xa5\x1ab\x00\x00\x00\x04\x00\x00\x00\x01\x00\x00\x00\xff\xdb\xa5\x1ab\x00\x00\x00\x05\x00\x00\x00\x01\x00\x00\x00\xe9\xdc\xa5\x1ab\x00\x00\x00\x06\x00\x00\x00\x02\x00\x00\x00\xf7\xdc\xa5\x1ab\x00\x00\x00\x08\x00\x00\x00\x02\x00\x00\x00\x1b\xdd\xa5\x1a') and I'm taking the file as user input and reading the file in the read_file variable( class bytes object).I need to convert it to ascii using an integer schema (int, int, int, int) each int of 4 bytes. I was trying doing this using struct library to unpack it. I wrote the following commands but it gave me following error:

error

print(unpack("IIII", read_file))
struct.error: unpack requires a buffer of 16 bytes

code

    for (dirpath, dirnames, filenames) in walk('/Users/amathur1/PycharmProjects/learningpython/NAWF_VRG_G'):
        count = 1
        for file in filenames:
            print(count, " : ", file)
            count = count + 1
        print("select file you want to convert")
        input_file = input()
        print("Selected file number is : ", input_file)

        #To open the selected file
    with open(dirpath + "/" + filenames[int(input_file) - 1], 'rb') as file:
        # Reading the selected file i.e. file
        read_file = file.read()
    print(unpack("IIII", read_file))

Upvotes: 7

Views: 79460

Answers (2)

Bakkom
Bakkom

Reputation: 77

You can also get that error if you use a corrupt/broken file, or a file with the wrong file extension. Also happens if you convert between file formats in the wrong way. It obviously gets a little confused if you hand it a png file with a .ico file extension in it's name for example.

Upvotes: 3

Scott Hunter
Scott Hunter

Reputation: 49803

Your file appears to be bigger than the size of 4 ints (16 bytes); if, as you say, each set of 4 ints needs to be converted, then you'll have to break of the data from the file into a sequence of chunks that size.

Upvotes: 7

Related Questions