将二进制读取函数从C++转换为C#

本文关键字:转换 C++ 二进制 读取 函数 | 更新日期: 2023-09-27 18:27:56

老实说,我在阅读C#中的二进制文件时真的很困惑。我有用于读取二进制文件的C++代码:

FILE *pFile = fopen(filename, "rb");    
uint n = 1024;
uint readC = 0;
do {
    short* pChunk = new short[n];
    readC = fread(pChunk, sizeof (short), n, pFile);    
} while (readC > 0);

它读取以下数据:

-156, -154, -116, -69, -42, -36, -42, -41, -89, -178, -243, -276, -306,...

我尝试将此代码转换为C#,但无法读取此类数据。这是代码:

using (var reader = new BinaryReader(File.Open(filename, FileMode.Open)))
{
     sbyte[] buffer = new sbyte[1024];                
     for (int i = 0; i < 1024; i++)
     {
         buffer[i] = reader.ReadSByte();
     }                
}

我得到以下数据:

100, -1, 102, -1, -116, -1, -69, -1, -42, -1, -36 

如何获取类似的数据?

将二进制读取函数从C++转换为C#

short不是有符号的字节,而是有符号的16位值。

 short[] buffer = new short[1024];                
 for (int i = 0; i < 1024; i++) {
     buffer[i] = reader.ReadInt16();
 }

这是因为在C++中读取short,而在C#中读取有符号字节(这就是SByte的含义)。您应该使用reader.ReadInt16()

您的C++代码每次读取2个字节(您使用的是sizeof(short)),而您的C#代码每次读取一个字节。SByte(请参阅http://msdn.microsoft.com/en-us/library/d86he86x(v=vs.71).aspx)使用8位存储空间。

您应该使用相同的数据类型来获得正确的输出或转换为新类型。

在c++中,您使用的是short。(我假设该文件也是用short编写的),所以在c#中使用short本身。也可以使用Sytem.Int16

由于shortsbyte不相等,您得到的值不同。short是2字节,Sbyte是1字节

using (var reader = new BinaryReader(File.Open(filename, FileMode.Open)))
{
     System.Int16[] buffer = new System.Int16[1024];                
     for (int i = 0; i < 1024; i++)
     {
         buffer[i] = reader.ReadInt16();
     }                
}