-2
我試圖找到生成一定長度的隨機二進制字符串的最快方法。如在,一定數量的隨機布爾值。JavaScript/Node.JS中的隨機二進制文件
這是我目前的代碼 - 有沒有更快的方法?
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;
}
謝謝!