Christopher Chase
Christopher Chase

Reputation: 2890

Delphi, Copy string to Byte array

what i have works, but im looking if there is a faster way to copy a string into a pByteArray

from sysutils

  PByteArray = ^TByteArray;
  TByteArray = array[0..32767] of Byte;

assume a and s are setup correctly

 a:   pByteArray;
 s:   string;

is there a fast way to do this, ie something like copy

  for i := 1 TO Length(s) - 1 do
   a^[i] := Ord(s[i]);

delphi 7

Upvotes: 4

Views: 31049

Answers (4)

Chau Chee Yang
Chau Chee Yang

Reputation: 19620

Beware using the Move. If you are using Delphi 2009, it may fail. Instead, use this:

Move(s[1], a^, Length(s) * SizeOf(Char));

You may also use class TEncoding in SysUtils.pas (Delphi 2009/2010++ only) to perform the task.

Upvotes: 9

Remko
Remko

Reputation: 7330

You can simply cast it:

  a := @s[1];

The other way around is:

  s := PChar(a);

Upvotes: 4

Michał Niklas
Michał Niklas

Reputation: 54302

I think you can use move procedure just like in this example

Upvotes: 1

Christopher Chase
Christopher Chase

Reputation: 2890

never mind, found it

 Move(s[1], a^, Length(s));

Upvotes: 2

Related Questions