How to use TFileStream to read 2D matrices into a dynamic array?

I need to read a large (2000x2000) matrix of binary data from a file into a dynamic array with Delphi 2010. I do not know the sizes until runtime.

I have never read raw data like this and I do not know IEEE, so I am posting this to find out if I am on the go.

I plan to use TFileStream to read one line at a time.

I need to be able to read as many of these formats as possible:

 16-bit two complement binary integer
 32-bit two complement binary integer
 64-bit two complement binary integer
 IEEE single precision floating-point

For the 32-bit two add-ons, I think something like the code below. The transition to Int64 and Int16 should be straightforward. How can I read IEEE?

Am I on the right track? Any suggestions for this code, or how to gracefully extend it for all 4 data types above? Since after reading this data my post-processing will be the same, I think I will have to copy the matrix to the general format when this is done.

I have no problem with four procedures (one for each data type), like one of them, but maybe there is an elegant way to use RTTI or buffers, and then move () so that the same code works for all 4 types data?

Thank!

  type
    TRowData = array of Int32;

   procedure ReadMatrix;
   var
     Matrix: array of TRowData;
     NumberOfRows: Cardinal;
     NumberOfCols: Cardinal;
     CurRow: Integer;
   begin
     NumberOfRows := 20; // not known until run time
     NumberOfCols := 100; // not known until run time
     SetLength(Matrix, NumberOfRows);
     for CurRow := 0 to NumberOfRows do
       begin
         SetLength(Matrix[CurRow], NumberOfCols);
         FileStream.ReadBuffer(Matrix[CurRow], NumberOfCols * SizeOf(Int32)) );
       end;
   end;
+2
source share
1 answer

No, AFAIK there is no way to use RTTI to configure multidimensional arrays. But if you are using Delphi 2010, you should use generics, for example:

type
  TRowData<T> = array of T;

 procedure ReadMatrix<T>;
 var
   Matrix: array of TRowData<T>;
   NumberOfRows: Cardinal;
   NumberOfCols: Cardinal;
   CurRow: Integer;
 begin
   NumberOfRows := 20; // not known until run time
   NumberOfCols := 100; // not known until run time
   SetLength(Matrix, NumberOfRows, NumberOfCols);
   for CurRow := 0 to NumberOfRows do
     FileStream.ReadBuffer(Matrix[CurRow][0], NumberOfCols * SizeOf(T)) );
 end;

, Delphi 2010 . , , TWhateverClass.ReadMatrix<integer>, TWhateverClass.ReadMatrix<int64>, TWhateverClass.ReadMatrix<single> ..

, X, X SetLength, . SetLength(Matrix, NumberOfRows, NumberOfCols) , , .

+4

All Articles