Search code examples
javascriptrandomarraybuffer

How do I set specific ranges of an ArrayBuffer to random numbers?


I would like to set the first 29 bits of a 16-byte ArrayBuffer to a random value in the range [0, 2^28 - 1], independently of the system endianness.

Following is my attempt, but this (potentially) sets all 32 bits. What can I do? Is there a way to do something like randomNumberHere & 0x1FFFFFFF?

let buffer = new ArrayBuffer(16);
let view = new Uint32Array(buffer.slice(0, 4));
window.crypto.getRandomValues(view);

Solution

  • Here is what I have done. A little longer, but also more straightforward.

    import crypto from 'crypto';
    
    let buffer = new ArrayBuffer(16);
    
    let randomValue = crypto.randomInt(0, (1 << 29) - 1);
    let view = new DataView(buffer);
    view.setUint32(0, randomValue);