Well,
In fact, what exactly I want to do is to optimize the speed of the binary file reading.
My file structure is:
N times
- a Header of 64 "4-bytes integer"
- Samples of X "4-Bytes float IEEE" (so single, but variable array lenght)
One set of (Header + samples) are a multiple of 512 bytes. (I think this was due to network communications years ago, but standard remain)
So this is now my code:
unit ReadBin;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
TForm1 = class(TForm)
BtnRun: TButton;
DlgOpenBin: TOpenDialog;
procedure BtnRunClick(Sender: TObject);
private
procedure SwapByte(ToSwap: boolean; var BytesToSwap: Array of int32);
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
const
HeadSize = 64;
type
TData= Array of int32;
TSamples= Array of single;
var
BinFile: TFileStream;
TraceSize: integer;
Data: TData;
Samples: TSamples absolute Data;
IsBigEndian: boolean;
{ TForm1 }
procedure TForm1.BtnRunClick(Sender: TObject);
var
abyte: byte = 0;
nbjd, test: integer;
begin
DlgOpenBin.Filter:= 'Bin file | *.bin';
if DlgOpenBin.Execute then
begin
SetLength(Data, HeadSize);
BinFile:= TFileStream.Create(DlgOpenBin.Files[0], fmOpenRead);
try
BinFile.Seek(40, soFromBeginning);
BinFile.Read(abyte, 1);
IsBigEndian:= (abyte > 20);
BinFile.Seek(0, soFromBeginning);
BinFile.ReadBuffer(Pointer(Data)^, HeadSize * 4);
SwapByte(IsBigEndian, Header);
TraceSize:= (((Data[9] * 1000) div Data[8]) + 64) * 4;
TraceSize:= (TraceSize + (512 - TraceSize mod 512)) div 4;
BinFile.Seek(0, soFromBeginning);
SetLength(Data, TraceSize);
BinFile.ReadBuffer(Pointer(Data)^, TraceSize * 4);
SwapByte(IsBigEndian, Data);
.....
finally
BinFile.Free;
end;
end;
end;
procedure TForm1.SwapByte(ToSwap: boolean; var BytesToSwap: Array of int32);
var
i: integer;
begin
if ToSwap then
for i:= 0 to Length(BytesToSwap) -1 do BytesToSwap[i]:= SwapEndian(BytesToSwap[i]);
end;
end.
With your example, I can read my data as integer or as single, so it is perfect.
Doing like this allows me also to use the same swap byte function, regardless the type of data.
While typing this post, I optimize also my code, removing useless remaining declarations.
I'll give a try to your second example.
Thanks a lot
Cheers