Is there a way to add a byte to the beginning of TIdBytes variable in delphi without a loop?

StackOverflow https://stackoverflow.com/questions/23566319

  •  19-07-2023
  •  | 
  •  

Question

I have a TIdBytes variable myBytesArray and I'd like to add a byte to its beginning. I tried with a loop (although I'd definitely prefer a non-loop solution), but it still didn't work :

myBytesArray : TIdBytes;
// ...
len := Length(myBytesArray);
SetLength(myBytesArray, len + 1);
for i := len downto 1 do begin
  myBytesArray[i] := myBytesArray[i-1];
end;
myBytesArray[0] := myNewByte;
Was it helpful?

Solution

TIdBytes is an Indy data type. Indy has many functions in the IdGlobal unit for manipulating TIdBytes, such as InsertByte():

InsertByte(myBytesArray, myNewByte, 0);

OTHER TIPS

You can fix your loop by using index i rather than len:

for i := len downto 1 do 
  myBytesArray[i] := myBytesArray[i-1];

Your code copies the byte at len every time.

However, you can write a version without a loop using the Move procedure like this:

SetLength(myBytesArray, len + 1);
if len > 0 then
  Move(myBytesArray[0], myBytesArray[1], len);
myBytesArray[0] := myNewByte;

The if statement is needed if range checking is enabled.

As Remy says, the IdGlobal unit already provides the functionality that you need with the InsertByte procedure.

InsertByte(myBytesArray, myNewByte, 0);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top