-2

I am trying to find the fastest way of generating a random binary string of a certain length. As in, a certain number of random booleans.

Here's my current code - is there a much faster way?

function getRandomBits(n){
    var generator = crypto.pseudoRandomBytes;
    var generated = "";
    while(generated.length < n){
        var randomBytes = generator(4).readUInt32BE(0, true).toString(2);
        //Remove first byte as this is always one and so not random
        randomBytes = randomBytes.substring(1, randomBytes.length - 1);
        if(n - generated.length > randomBytes.length) generated = generated + randomBytes;
        else generated = generated + randomBytes.substring(0, n - generated.length);
    }
    console.log(generated);
    return generated;
}

Thanks!

1 Answer 1

2

It is unclear what "random booleans" means.

Just get the number of byte you need without going through an integer conversion.

From the node.js documentation:

const buf = crypto.randomBytes(256);

The crypto.randomBytes() method will block until there is sufficient entropy. This should normally never take longer than a few milliseconds. The only time when generating the random bytes may conceivably block for a longer period of time is right after boot, when the whole system is still low on entropy.

If you need some other form just post-process the bytes, each bit is essentially random.

Note: Although the function is named getRandomBits(n) it seems to be actually getting n bytes, not n bits.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.