Thread overview
How to cast arrays?
Mar 02, 2019
Murilo
Mar 02, 2019
Matheus
Mar 02, 2019
H. S. Teoh
Mar 02, 2019
Matheus
March 02, 2019
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.
March 02, 2019
On Saturday, 2 March 2019 at 02:14:01 UTC, Murilo 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.

https://dlang.org/spec/expression.html#cast_expressions

"Casting a dynamic array to another dynamic array is done only if the array lengths multiplied by the element sizes match. The cast is done as a type paint, with the array length adjusted to match any change in element size. If there's not a match, a runtime error is generated."

Matheus.
March 01, 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
March 02, 2019
On Saturday, 2 March 2019 at 02:14:01 UTC, Murilo 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.

By the way here is how:

void foo(){
   ubyte[] x = [1,2];
   auto y = (cast(int*) &x)[0..2];
   writeln(y);
}

Matheus.