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

时间:2012-03-16 09:07:39

标签: c# c++ c c#-4.0

老实说,我真的很困惑在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 

我如何获得类似数据?

4 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

那是因为在C ++中你正在读短片而在C#中你正在读取有符号的字节(这就是SByte的意思)。您应该使用reader.ReadInt16()

答案 2 :(得分:2)

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

答案 3 :(得分: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();
     }                
}