c# - 如何将二进制文件头示例代码(C++/C#)转换为Python?

标签 c# python c++

我正在根据制造商的示例代码编写一个二进制文件来保存硬件仪器数据(Larson-Davis 831C)。我以下样本:

C++

string create_ldbin_header(int num_files, vector<int>& file_sizes)
{
ostringstream return_value;

int hdr1 = 'LD';
int hdr2 = 'BIN';
int hdr3 = 1;
int hdr4 = num_files;

return_value.write((char*)&hdr1, 4);
return_value.write((char*)&hdr2, 4);
return_value.write((char*)&hdr3, 4);
return_value.write((char*)&hdr4, 4);

for (int i = 0; i < num_files; ++i)
{
    return_value.write((char*)&file_sizes[i], 4);
}
return return_value.str();
}

C#中的另一个版本
private void WriteLDBinHeader(BinaryWriter writer, int fileSize)
        {
            writer.Write();
            writer.Write((Int32)0x0042494E);
            writer.Write((Int32)0x00000001);
            writer.Write((Int32)1);
            writer.Write((Int32)fileSize);
        }

我在Python中做同样的尝试失败了。我尝试了多个版本,但我对struct pack不熟悉。我认为以字符串表示的格式应为{0:032b}。无论如何,我的最后尝试是:
hdr1 = "LD"
hdr2 = 'BIN'
hdr3 = "1"
hdr4 =str(y[0]["size"])
header = struct.pack('=iiii',hdr1,hdr2,hdr3,hdr4)

with open('instrumentFile.ldbin', 'wb') as f:
    f.write(header + r.content)

翻译中的任何指导将不胜感激。

最佳答案

试试这个:

hdr1 = 0x00004c44  # "  LD"
hdr2 = 0x0042494e  # " BIN"
hdr3 = 1
hdr4 = int(y[0]["size"])
header = struct.pack('>iiii',hdr1,hdr2,hdr3,hdr4)

with open('instrumentFile.ldbin', 'wb') as f:
    f.write(header + r.content)

关于c# - 如何将二进制文件头示例代码(C++/C#)转换为Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59537724/

相关文章:

python - 用 Python 编写游戏循环的正确方法是什么?

python - 使用 lxml 从 xml 中提取嵌套命名空间

c++ - 是否在非数组指针的末尾创建一个指针,该指针不是从 C++17 中的一元运算符和未定义行为派生的?

c++ - 尝试使用新构造函数和复制构造函数分配内存时获取 "expected unqualified-id before ‘(’ token

c++ - vector 的初始化

c# - 在 DataGridView 中隐藏滚动条

c# - 如何将此条件写入 NHibernate HBM 映射?

c# - 如何使用 FirstAsync 在 Entity Framework Core 中处理 null?

c# - c# arraylist 中的对象

python - 如何在 Python Selenium 中以随机间隔使用 send_keys ?