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

3

我在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++中,你将每个实体读取为“short”,它是2个字节,而在C#中,你将每个实体读取为“sbyte”,它是1个字节。 - Jason
@Jason 在C++中,short的大小并没有完全定义好;p 但是:我不反对。你应该把它作为一个答案添加进去。 - Marc Gravell
我不知道,没有C++经验 ;/ - Jason
在C++示例中,您正在读取短数据类型,而在C#示例中,您正在使用有符号字节,数据范围要小得多。您尝试将C#示例中的sbyte更改为short了吗? - display101
实际上,-178、-243、-306等完全超出了sbyte范围,所以作为sbyte是永远不会起作用的。 - Marc Gravell
4个回答

2

short并不是有符号字节,它是一个有符号的16位值。

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

2

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


2

1

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

在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();
     }                
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接