2012-03-16 99 views
3

对于阅读C#中的二进制文件,我确实很困惑。 我有C++代码读取二进制文件:将二进制读取函数从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 

我怎样才能得到类似的数据?

+0

在C++中,你正在阅读的每个实体作为'short',其为2个字节,而在C#中,正在阅读的每个实体作为'sbyte'这是1个字节。 – Jason 2012-03-16 09:12:32

+0

@Jason肯定在C++中'short'的大小没有完全定义; p但是:我不反对。你应该添加这个答案。 – 2012-03-16 09:12:43

+0

我不知道,没有C++经验;/ – Jason 2012-03-16 09:13:06

回答

2

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

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

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

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