Convert some ints into a byte array without allocations?
Johannes Pfau via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Jan 16 11:19:08 PST 2016
Am Sat, 16 Jan 2016 15:46:00 +0000
schrieb Samson Smith <fsdf at dsfd.com>:
> On Saturday, 16 January 2016 at 14:42:27 UTC, Yazan D wrote:
> > On Sat, 16 Jan 2016 14:34:54 +0000, Samson Smith wrote:
> >
> >> [...]
> >
> > You can do this:
> > ubyte[] b = (cast(ubyte*) &a)[0 .. int.sizeof];
> >
> > It is casting the pointer to `a` to a ubyte (or byte) pointer
> > and then taking a slice the size of int.
>
> This seems to work. Thankyou!
You need to be careful with that code though. As you're taking the
address of the a variable, b.ptr will point to a. If a is on the stack
you must make sure you do not escape the b reference.
Another option is using static arrays:
ubyte[a.sizeof] b = *(cast(ubyte[a.sizeof]*)&a);
Static arrays are value types. Whenever you pass b to a function it's
copied and you don't have to worry about the lifetime of a.
This pointer cast (int => ubyte[4]) is safe, but the inverse operation,
casting from ubyte[4] to int, is not safe. For the inverse operation
you'd have to use unions as shown in Yazans response.
More information about the Digitalmars-d-learn
mailing list