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

Posted by Robert Frank on Stack Overflow See other posts from Stack Overflow or by Robert Frank
Published on 2010-05-20T22:02:37Z Indexed on 2010/05/20 22:20 UTC
Read the original article Hit count: 178

Filed under:

I need to read a large (2000x2000) matrix of binary data from a file into a dynamic array with Delphi 2010. I don't know the dimensions until run-time.

I've never read raw data like this, and don't know IEEE so I'm posting this to see if I'm on track.

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

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

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

For 32-bit two's complement, I'm thinking something like the code below. Changing to Int64 and Int16 should be straight forward. How can I read the IEEE?

Am I on the right track? Any suggestions on this code, or how to elegantly extend it for all 4 data types above? Since my post-processing will be the same after reading this data, I guess I'll have to copy the matrix into a common format when done.

I have no problem just having four procedures (one for each data type) like the one below, but perhaps there's an elegant way to use RTTI or buffers and then move()'s so that the same code works for all 4 datatypes?

Thanks!

  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;

© Stack Overflow or respective owner

Related posts about delphi