生成一个 256 位的随机数
Generate a 256 bit random number
我需要生成一个 256 位随机无符号数作为十进制字符串(与之前生成的任何内容发生冲突的概率几乎为零)。
如何在 JavaScript(浏览器)中执行此操作?
此代码使用循环生成 256 个字符长的随机二进制数字字符串,然后将其转换为 BigInt
。然后,您可以根据需要将其转换为字符串,或者您喜欢的任何其他内容。
var temp = '0b';
for (let i = 0; i < 256; i++) {
temp += Math.round(Math.random());
}
const randomNum = BigInt(temp);
console.log(randomNum.toString());
如果您不是很受限,您可以使用新的 JavaScript 工具:
function rnd256() {
const bytes = new Uint8Array(32);
// load cryptographically random bytes into array
window.crypto.getRandomValues(bytes);
// convert byte array to hexademical representation
const bytesHex = bytes.reduce((o, v) => o + ('00' + v.toString(16)).slice(-2), '');
// convert hexademical value to a decimal string
return BigInt('0x' + bytesHex).toString(10);
}
console.log( rnd256() );
我需要生成一个 256 位随机无符号数作为十进制字符串(与之前生成的任何内容发生冲突的概率几乎为零)。
如何在 JavaScript(浏览器)中执行此操作?
此代码使用循环生成 256 个字符长的随机二进制数字字符串,然后将其转换为 BigInt
。然后,您可以根据需要将其转换为字符串,或者您喜欢的任何其他内容。
var temp = '0b';
for (let i = 0; i < 256; i++) {
temp += Math.round(Math.random());
}
const randomNum = BigInt(temp);
console.log(randomNum.toString());
如果您不是很受限,您可以使用新的 JavaScript 工具:
function rnd256() {
const bytes = new Uint8Array(32);
// load cryptographically random bytes into array
window.crypto.getRandomValues(bytes);
// convert byte array to hexademical representation
const bytesHex = bytes.reduce((o, v) => o + ('00' + v.toString(16)).slice(-2), '');
// convert hexademical value to a decimal string
return BigInt('0x' + bytesHex).toString(10);
}
console.log( rnd256() );