python - 使用 C# BinaryReader 读取 python 二进制文件

标签 python c# binary binaryfiles

我需要使用 python 将一些数据(如整数、 float 等)导出到二进制文件。之后,我必须再次用 C# 读取该文件,但它对我不起作用。

我尝试了几种用 python 编写二进制文件的方法,只要我用 python 读取它,它就可以工作:

a = 3
b = 5

with open('test.tcd', 'wb') as file:
    file.write(bytes(a))
    file.write(bytes(b))

或者这样写:

import pickle as p

with open('test.tcd', 'wb') as file:
    p.dump([a, b], file)

目前我正在用 C# 读取文件,如下所示:

static void LoadFile(String path)
{
       BinaryReader br = new BinaryReader(new FileStream(path, FileMode.Open));
       int a = br.ReadInt32();
       int b = br.ReadInt32();

       System.Diagnostics.Debug.WriteLine(a);
       System.Diagnostics.Debug.WriteLine(b);

       br.Close();
}

不幸的是,输出不是 3 和 5,而是我的输出为零。如何正确读取或写入二进制文件?

最佳答案

在 Python 中,您必须每个整数写入 4 个字节。在这里阅读更多信息:struct.pack

a = 3
b = 5

with open('test.tcd', 'wb') as file:
     f.write(struct.pack("<i", 3))
     f.write(struct.pack("<i", 5))

您的 C# 代码现在应该可以运行了。

关于python - 使用 C# BinaryReader 读取 python 二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65361211/

相关文章:

python - pycharm 变量 Pane 中的隐藏值

python - 动态设置函数调用中包含的内容

python2.7 : no such file or directory after brew upgrade python3

c++ - 关于以二进制存储并显示其十进制

c - 用二进制表示无符号整数

python - virtualenv 中的 django 出现 apache mod_wsgi 错误

c# - WPF MenuItem 未填充可用的 ContextMenu 空间

c# - 生成不同 ID 的相同实体

c# - 如何通过 .NET 访问 ARP 协议(protocol)信息?

python - 将输入分解为列出的频率