Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从C+转换二进制读取函数+;到C#_C#_C++_C_C# 4.0 - Fatal编程技术网

从C+转换二进制读取函数+;到C#

从C+转换二进制读取函数+;到C#,c#,c++,c,c#-4.0,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, -1

老实说,我在读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,...
100, -1, 102, -1, -116, -1, -69, -1, -42, -1, -36 
我尝试将此代码转换为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();
     }                
}

如何获得类似的数据?

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

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

<>代码> < P>这是因为在C++中,你正在阅读短裤,而在C语言中,你正在阅读有符号的字节(这就是SByte的意思)。你应该使用<代码> Reader。ReadIt1616()/Cux>

< P>你的C++代码每次读取2字节(你使用sieof(短)),而你的C代码每次读取一个字节。SByte(请参阅)使用8位存储。

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

C++中使用的是<代码>短<代码>。(我假设该文件也是用
short
编写的)因此在c#中使用
short
本身。或者您可以使用
system.Int16

您得到的值不同,因为
short
sbyte
不相等
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();
     }                
}
使用(var reader=newbinaryreader(File.Open(filename,FileMode.Open)))
{
System.Int16[]buffer=new System.Int16[1024];
对于(int i=0;i<1024;i++)
{
buffer[i]=reader.ReadInt16();
}                
}

在C++中,你将每个实体都看作是短/<代码>,这是2字节,而在C语言中,你把每个实体都看作是<代码>字节By/Cube >,这是1字节。@杰森在C++中肯定没有定义“代码>短< /Cord>”的大小;p:但我并不反对。你应该把它作为答案,我不知道,没有C++经验;在C++示例中,您正在读取短数据类型,而在C示例中,使用的是符号字节,数据范围要小得多。在C#示例中,您是否尝试过将sbyte改为short?事实上,-178,-243,-306等完全超出了
sbyte
范围-因此,这永远不会像
sbyte