[fpc-pascal] Is there a Pos() function for TBytes?

Michael Van Canneyt michael at freepascal.org
Thu Apr 20 08:40:48 CEST 2023

On Thu, 20 Apr 2023, Bo Berglund via fpc-pascal wrote:

> I am transferring data via serial comm and they wind up inside a TBytes dyn
> array.
> Now I want to easily find a certain pattern of bytes inside that array, but how?
> I have a cludge that does not feel right but works and I want to get it replaced
> by the "correct" way of doing it.
> So what I have done so far is the following kind of thing using an AnsiString to
> supply the Pos() functionality:
> var
>  bData: TBytes;
>  sData: AnsiString;
>  p: integer;
> begin
>  GetSerialData(bData); //Load the array with incoming data
>  SetLength(sData, Length(bData); //Prepare string to receive data
>  Move(bData[0], sData[1], Length(bData)); //Copy all data
>  p := Pos(pattern, sData);
>  ...
> I'd rather use some built-in function that is *not* using intermediate strings
> but can operate on the TBytes array directly.
> I found this page:
> https://www.freepascal.org/docs-html/rtl/system/copy.html
> Here there is also reference to the other functions for strings:
> Delete  (string and dyn array)
> Copy    (string and dyn array)
> Insert  (string and dyn array but limited to 255 elements, why?)
> Pos     (string only..)
> They describe what can be done with strings and in some cases dynamic arrays
> (like TBytes?), but for Pos() there is only string...
> And Insert seems to have a limit of 255 elements, why?
> What I need is a Pos(token) for TBytes where the token can be a single or
> multiple bytes in size (just like for strings).
> Is there such a thing?

Not that I am aware of, but I think it would be a welcome addition to one of
the RTL units. I've been in need of such a function on multiple occasions,
and had to resort to custom code each time.


More information about the fpc-pascal mailing list