Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting binary reading function from C++ to C#

Tags:

c++

c

c#

c#-4.0

I am honestly really confused on reading binary files in C#. I have C++ code for reading binary files:

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

and it reads the following data:

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

I tried convert this code to C# but cannot read such data. Here is code:

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

and i get the following data:

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

How can i get similar data?

like image 225
Mirodil Avatar asked May 20 '26 10:05

Mirodil


2 Answers

A short is not a signed byte, it's a signed 16 bit value.

 short[] buffer = new short[1024];                
 for (int i = 0; i < 1024; i++) {
     buffer[i] = reader.ReadInt16();
 }
like image 190
Guffa Avatar answered May 22 '26 23:05

Guffa


That's because in C++ you're reading shorts and in C# you're reading signed bytes (that's why SByte means). You should use reader.ReadInt16()

like image 29
zmbq Avatar answered May 22 '26 23:05

zmbq