请问如何读取二进制文件,我用filestream读取的是一个byte数组,难道要将字节一个一个地转换为整形或浮点型吗?有没有直接从二进制文件中读取多个整形或浮点型数据的函数?

解决方案 »

  1.   

    我记得在哪看过的
    byte[] b;
    int c;c=b[0]+b[1]+b[2]+b[3]; 整型四个字节,不知道行不行不过共用体的话肯定是可以的,推荐用这个
    struct myunion
    {
    [FieldOffset(0)] int c;
    [FieldOffset(0)] byte b0;
    [FieldOffset(1)] byte b1;
    [FieldOffset(2)] byte b2;
    [FieldOffset(3)] byte b3;
    }//大概就这个意思吧,具体你在VS中就可以试出来了
      

  2.   

    use binaryReadereg: FileStream fs = new FileStream( dataFilePath, FileMode.Open, FileAccess.Read, FileShare.Read );
    BinaryReader br = new BinaryReader( fs );
    width = br.ReadInt32();
    height = br.ReadInt32();
      

  3.   

    我希望一次读出来多个整数或浮点数,就像C++中fread(dataPointer, sizeof(int), num, fp)一样,而不是每次只读取一个或每次通过字节转换一个数
      

  4.   

    用 BinaryReaderFileStream fs = new FileStream("xxx.bin", FileMode.Open, FileAccess.Read);
    BinaryReader br = new BinaryReader(fs);BinaryReader 的用法可以自己查一下 .NET Framework SDK 文档
      

  5.   

    BinaarReader 读取返回的是一个byte 的数组,怎样将他转换为整形数组啊?如下所示,效率太低了
    Byte []pByte = new Byte[512]; FileStream fs = new FileStream("F:\\data\\SL.3D.GSHANG11", FileMode.Open, FileAccess.Read); // Read data from Test.data.
    for (int i = 0; i < 1; i++) 
    {
    fs.Read(pByte, 0, 512); for(int j = 0; j < 128; j++)
    {
    int mm = BitConverter.ToInt32(pByte, j*4);
    }
    }
    fs.Close();
      

  6.   

    binaryReader本身的效率很不错了,它可以直接读成int的,不需要从BitConverter去转换FileStream fs = new FileStream( dataFilePath, FileMode.Open, FileAccess.Read, FileShare.Read );
    BinaryReader br = new BinaryReader( fs );
    width = br.ReadInt32();
    height = br.ReadInt32();
    int [,,] cellData = new int[ width, height ];
    for ( int j = 0 ; j < width; j++ )
    {
    for ( int i = 0 ; i < height; i++ )
    {
    cellData[z,i,j] = br.ReadInt32();
    }
    }
      

  7.   

    sorryint [,,] cellData = new int[ width, height ];
    ==>
    int [,] cellData = new int[ width, height ];cellData[z,i,j] = br.ReadInt32();
    ==>
    cellData[i,j] = br.ReadInt32();