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:42:27 PST 2016


On Sat, 16 Jan 2016 14:34:54 +0000, Samson Smith wrote:

> I'm trying to make a fast little function that'll give me a random
> looking (but deterministic) value from an x,y position on a grid. I'm
> just going to run each co-ord that I need through an FNV-1a hash
> function as an array of bytes since that seems like a fast and easy way
> to go. I'm going to need to do this a lot and quickly for a real time
> application so I don't want to waste a lot of cycles converting data or
> allocating space for an array.
> 
> In a nutshell how do I cast an int into a byte array?
> 
> I tried this:
> 
> byte[] bytes = cast(byte[])x;
>> Error: cannot cast expression x of type int to byte[]
> 
> What should I be doing instead?

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.


More information about the Digitalmars-d-learn mailing list