2013-07-18 40 views
0

我已經分配了將C++應用程序轉換爲C#。將C++轉換爲C#將二進制文件讀入二維浮點數組

我想在C#中轉換以下代碼,其中rate_buff是雙[3,9876]二維數組。

if ((fread((char*) rate_buff, 
          (size_t) record_size, 
          (size_t) record_count, 
          stream)) == (size_t) record_count) 
+0

和你的問題是什麼? – madnut

+0

需要將上面的代碼轉換爲C#。 –

回答

4

如果我猜對了你的要求,這是你想要什麼:

int record_size = 9876; 
int record_count = 3; 

double[,] rate_buff = new double[record_count, record_size]; 

// open the file 
using (Stream stream = File.OpenRead("some file path")) 
{ 
    // create byte buffer for stream reading that is record_size * sizeof(double) in bytes 
    byte[] buffer = new byte[record_size * sizeof(double)]; 

    for (int i = 0; i < record_count; i++) 
    { 
     // read one record 
     if (stream.Read(buffer, 0, buffer.Length) != buffer.Length) 
      throw new InvalidDataException(); 

     // copy the doubles out of the byte buffer into the two dimensional array 
     // note this assumes machine-endian byte order 
     for (int j = 0; j < record_size; j++) 
      rate_buff[i, j] = BitConverter.ToDouble(buffer, j * sizeof(double)); 
    } 
} 

或者更簡潔地用BinaryReader在:

int record_size = 9876; 
int record_count = 3; 

double[,] rate_buff = new double[record_count, record_size]; 

// open the file 
using (BinaryReader reader = new BinaryReader(File.OpenRead("some file path"))) 
{ 
    for (int i = 0; i < record_count; i++) 
    { 
     // read the doubles out of the byte buffer into the two dimensional array 
     // note this assumes machine-endian byte order 
     for (int j = 0; j < record_size; j++) 
      rate_buff[i, j] = reader.ReadDouble(); 
    } 
}