How to cast arrays?
H. S. Teoh
hsteoh at quickfur.ath.cx
Sat Mar 2 02:23:46 UTC 2019
On Sat, Mar 02, 2019 at 02:14:01AM +0000, Murilo via Digitalmars-d-learn wrote:
> How do I cast a ubyte[] into uint[]? It keeps raising an error, I have
> read the documentation saying there are restrictions for that
> concerning the length of the arrays.
That depends on what you're trying to accomplish. Are you trying to
*reinterpret* the ubytes as uints? I.e., every 4 ubytes will be
interpreted as 1 uint? If so, cast(uint[]) is your ticket. And
obviously it will require that the .length of the ubyte[] must be a
multiple of uint.sizeof, since otherwise the last element would be
malformed. And there will probably be alignment issues as well.
However, if you're trying to *transcribe* ubyte values into uint, i.e.,
promote each ubyte value to uint, then what you want is NOT a cast, but
a transcription, i.e., copy ubytes into uint with integer promotion.
There are various ways of doing this; an obvious one is:
ubyte[] bytes = ...;
uint[] ints = bytes.map!(b => cast(uint) b).array;
T
--
Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald Knuth
More information about the Digitalmars-d-learn
mailing list