Casting int[] to ubyte[]: element wise cast or slice cast
Dennis
dkorpel at gmail.com
Fri Feb 15 16:17:12 UTC 2019
I assumed that casting an int[] to a ubyte[] would keep all bytes
and quadruple the length of the original array. But when the
array is a literal, it keeps the same length but truncates every
int element to a ubyte:
```
import std.stdio;
void main()
{
// enum:
enum litA = [0x10203040, 0x50607080];
pragma(msg, typeof(litA));
ubyte[] a = cast(ubyte[]) litA;
// auto:
auto litB = [0x10203040, 0x50607080];
pragma(msg, typeof(litB));
ubyte[] b = cast(ubyte[]) litB;
writeln(a);
writeln(b);
}
```
Prints:
```
int[]
int[]
[64, 128]
[64, 48, 32, 16, 128, 112, 96, 80]
```
I looked at the spec and found this:
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."
So is this a bug or am I missing something?
More information about the Digitalmars-d-learn
mailing list