Reputation: 1368
How do I assign a TArray<Byte>
to array of Byte
and vice versa?
TEncoding.UTF8.GetBytes
returns a TArray<Byte>
. TIdHashMessageDigest5.HashBytes
has a TIdBytes = array of Byte
as parameter.
Can I assign these types to each other? Maybe with a copy? Or do I need to loop?
Upvotes: 6
Views: 1700
Reputation: 612954
These types are not assignment compatible. In an ideal world you would use TArray<T>
exclusively, and it would be better if all libraries did so. I do not understand why Indy insists on using its own distinct type here.
If you cannot then you can make a copy. That's easy enough with a loop. If efficiency matters that you could copy using Move
.
SetLength(Dest, Length(Source));
Move(Pointer(Source)^, Pointer(Dest)^, Length(Source));
I use Pointer(arr)^
here rather than arr[0]
to avoid tripping range check exceptions in case of an empty array.
It is also possible to avoid a copy by using a typecast, since all dynamic arrays are implemented the same way. So you could write
Hash := HashBytes(TIdBytes(TEncoding.UTF8.GetBytes(...)));
Of course, this gives up type safety, but then so does the call to Move
above.
Yet another approach, suggested by Remy's answer to another question, is to use TIdTextEncoding
rather than TEncoding
. That way you can work with TIdBytes
exclusively.
Upvotes: 8