读取 python 中的二进制文件时跳过第一个字节

First byte skipped when reading binary file in python

我想读入一个二进制文件并根据其内容生成一个 c 初始值设定项。然而,不知何故,第一个字节似乎总是被我的读取过程跳过。你能帮我看看为什么会这样吗?

该文件在二进制文件中以 0x4c 开头,但我从未在以下 python 代码的输出中看到它:

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");

感谢您对此问题的任何帮助。

问题是:

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.

您应该将其更改为:

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");