Casting int to ubyte: element wise cast or slice cast
H. S. Teoh
hsteoh at quickfur.ath.cx
Fri Feb 15 17:18:28 UTC 2019
On Fri, Feb 15, 2019 at 04:17:12PM +0000, Dennis via Digitalmars-d-learn wrote:
> 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
That's correct. If you want to *transcribe* a ubyte to an int, what
you want is probably something like this:
import std.conv : to;
ubyte data = ...;
int result = data.map!(b => b.to!int).array;
> I looked at the spec and found this:
> "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?
Read it again carefully: the casting is done "only if the array lengths
multiplied by the element sizes match". In other words:
T.sizeof * T.length == U.sizeof * U.length
Why? because that's the only case where you can reinterpret the
.sizeof*.length bytes as an array of a different type. There is no
conversion, the cast works as a reinterpretation. It's by design.
I'm still trying to find a pun for "punishment"...
More information about the Digitalmars-d-learn