简体   繁体   English

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

[英]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.我想读入一个二进制文件并从其内容中生成一个 c 初始化程序。 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:该文件以二进制文件中的 0x4c 开头,但我从未在以下 python 代码的 output 中看到这一点:

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.感谢您对此问题的任何帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM