Converting binary read function from C ++ to C #

To be honest, I am really confused about reading binaries in C #. I have C ++ code for reading binaries:

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 have tried converting this code to C # but cannot read data like this. Here is the 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 will get the following data:

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

      

How can I get similar data?

+3


source to share


4 answers


The short value is not a signed byte, it corresponds to a 16 bit value.



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

      

+2


source


This is because in C ++ you read shorts, and in C # you read signed bytes (which means SByte). You must usereader.ReadInt16()



+2


source


Your C ++ code reads 2 bytes at a time (you are using sizeof (short)), while your C # code reads one byte at a time. SByte (see http://msdn.microsoft.com/en-us/library/d86he86x(v=vs.71).aspx ) uses 8 bits of memory.

+2


source


You have to use the same data type to get correct output or apply to a new type.

In C ++, you are using short

. (assuming the file is also written with short

), so use short

directly in C #. or you can use Sytem.Int16

.

You get different values ​​because short

and are sbyte

not equivalent. short

- 2 bytes, and sbyte

- 1 byte

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

      

+1


source







All Articles