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
  •  | 
  •  

문제

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;
도움이 되었습니까?

해결책

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

InsertByte(myBytesArray, myNewByte, 0);

다른 팁

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top