Search code examples
arraysdelphiindexingcompare

Comparing arrays in Delphi


I have 3 arrays, for example:

const
  A: Array[0..9] of Byte = ($00, $01, $AA, $A1, $BB, $B1, $B2, $B3, $B4, $FF);
  B: Array[0..2] of Byte = ($A1, $BB, $B1);
  C: Array[0..2] of Byte = ($00, $BB, $FF);

Is there a way to compare and get the index of the right one, instead of checking each byte 1 by 1? For example:

function GetArrayIndex(Source, Value: Array of Byte): Integer;
begin
..
end;

GetArrayIndex(A, B); // results 3
GetArrayIndex(A, C); // results -1

Thank you in advance.


Solution

  • function ByteArrayPos(const SearchArr : array of byte; const CompArr : array of byte) : integer;
    //  result=Position or -1 if not found
    var
      Comp,Search : AnsiString;
    begin
      SetString(Comp, PAnsiChar(@CompArr[0]), Length(CompArr));
      SetString(Search, PAnsiChar(@SearchArr[0]), Length(SearchArr));
      Result := Pos(Search,Comp) - 1;
    end;