Steve
Steve

Reputation: 73

First byte skipped when reading binary file in python

I want to read in a binary file and produce a c initializer out of its content. However somehow the first byte always seems to be skipped by my read procedure. Can you help me why this is happening?

The file begins with a 0x4c in the binary, but I never see this in the output of the following python code:

f = open("GoldenFPGA.bit", "rb")
count = 0
print("#ifndef __CL_NX_BITSTREAM_HEADER_H");
print("#define __CL_NX_BITSTREAM_HEADER_H");
print("const uint8_t cl_nx_bitstream[] = ");
print("{");
print("    0x7A, 0x00, 0x00, 0x00,");
print("    ", end='')
try:
    byte = f.read(1)
    while byte:
        # Do stuff with byte.
        byte = f.read(1)
        if byte:
            print("0x" + byte.hex() + ", ", end='')
        count = count + 1
        if count % 8 == 0:
            print("\n    ", end='')
finally:
    f.close()
print("\n};");
print("#endif");

Thanks for any help on this issue.

Upvotes: 2

Views: 453

Answers (1)

David
David

Reputation: 8318

The problem is:

You read the first byte before the loop, and when you enter the loop you read another byte -> causing you to skip the first byte.

You should change it to:

f = open("GoldenFPGA.bit", "rb")
count = 0
print("#ifndef __CL_NX_BITSTREAM_HEADER_H");
print("#define __CL_NX_BITSTREAM_HEADER_H");
print("const uint8_t cl_nx_bitstream[] = ");
print("{");
print("    0x7A, 0x00, 0x00, 0x00,");
print("    ", end='')
try:
    byte = f.read(1)
    while byte:
        # Do stuff with byte.
        if byte:
            print("0x" + byte.hex() + ", ", end='')
        count = count + 1
        if count % 8 == 0:
            print("\n    ", end='')
        # read next byte
        byte = f.read(1)
finally:
    f.close()
print("\n};");
print("#endif");

Upvotes: 3

Related Questions