Convert some ints into a byte array without allocations?
Yazan D via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Jan 16 06:46:47 PST 2016
On Sat, 16 Jan 2016 14:42:27 +0000, Yazan D 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.
You can also use a union:
union Foo
{
int i;
ubyte[4] b;
}
// write to int part
Foo f = Foo(a);
// then read from ubyte part
writeln(foo.b);
ps. I am not sure of the aliasing rules in D for unions. In C, this is
allowed, but in C++, this is undefined behaviour AFAIK.
More information about the Digitalmars-d-learn
mailing list