How to do "cast(ubyte[4])some_uint" in D1?
Steven Schveighoffer
schveiguy at yahoo.com
Thu Jun 2 03:38:07 PDT 2011
On Thu, 02 Jun 2011 05:35:40 -0400, Nick Sabalausky <a at a.a> wrote:
> In D2, I can treat a uint as an array of ubytes by doing this:
>
> uint num = /+...whatever...+/;
> ubyte[] = cast(ubyte[4])num;
>
> How do I do that in D1?
>
> IIRC, D1 requires an explicit slice operator to convert from a
> static-array
> to a slice/dynamic-array, so I tried this:
>
> ubyte[] = (cast(ubyte[4])num)[];
>
> But I get the error:
> Error: e2ir: cannot cast num of type uint to type ubyte[4u]
We can learn from C here :)
ubyte[] x = (cast(ubyte *)&num)[0..4];
Essentially, pointers are *always* castable to one another, and do not go
through any translations. Go to pointer-land, then back, and all your
casts shall work. It's how C++'s reinterpret_cast works.
-Steve
More information about the Digitalmars-d-learn
mailing list