DelphiDabbler Code Snippets Database

Snippet Selection

The following snippets from the Code Snippets Database have been requested.

ByteArraysSameStart

Checks if two byte arrays B1 and B2 are equal for the first Count elements. False is returned if any array has less than Count elements. Count must be >= 1.

function ByteArraysSameStart(const B1, B2: array of Byte; const Count: Integer):
  Boolean;
var
  I: Integer;
begin
  Assert(Count > 0, 'Count must be >= 1');
  Result := False;
  if (Length(B1) < Count) or (Length(B2) < Count) then
    Exit;
  for I := 0 to Pred(Count) do
    if B1[I] <> B2[I] then
      Exit;
  Result := True;
end;

IndexOfByte

Returns the index of the first occurrence of byte B in byte array A, or -1 if B is not in A.

function IndexOfByte(const B: Byte; const A: array of Byte): Integer;
var
  I: Integer;
begin
  Result := -1;
  for I := 0 to Pred(Length(A)) do
  begin
    if A[I] = B then
    begin
      Result := I;
      Exit;
    end;
  end;
end;

LastIndexOfByte

Returns the index of the last occurrence of byte B in byte array A, or -1 if B is not in A.

function LastIndexOfByte(const B: Byte; const A: array of Byte): Integer;
var
  I: Integer;
begin
  Result := -1;
  for I := Pred(Length(A)) downto 0 do
  begin
    if A[I] = B then
    begin
      Result := I;
      Exit;
    end;
  end;
end;

PopByteArray

Removes the last element of byte array A and returns the element. The length of A shrinks by one. A must not be empty.

function PopByteArray(var A: TBytes): Byte;
begin
  Assert(Length(A) > 0, 'A must be a non-empty array');
  Result := A[Pred(Length(A))];
  SetLength(A, Length(A) - 1);
end;

PushByteArray

Pushes byte B onto the end of byte array A. The length of A grows by one.

procedure PushByteArray(const B: Byte; var A: TBytes);
begin
  SetLength(A, Length(A) + 1);
  A[Pred(Length(A))] := B;
end;

ShiftByteArray

Removes the first element of byte array A and returns the element. The length of A shrinks by one. A must not be empty.

function ShiftByteArray(var A: TBytes): Byte;
begin
  Assert(Length(A) > 0, 'A must be a non-empty array');
  Result := A[0];
  Move(A[1], A[0], Length(A) - 1);
  SetLength(A, Length(A) - 1);
end;

UnShiftByteArray

Inserts byte B at the beginning of byte array A. The length of A grows by one.

procedure UnShiftByteArray(const B: Byte; var A: TBytes);
begin
  SetLength(A, Length(A) + 1);
  Move(A[0], A[1], Length(A) - 1);
  A[0] := B;
end;

View the whole database.

Go to the DelphiDabbler website.