C ++ to C#将二进制文件读入二维浮点数组

时间:2013-07-18 16:18:38

标签: 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)

1 个答案:

答案 0 :(得分: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();
    }
}