Created
July 23, 2024 22:44
-
-
Save missinglink/7e52209febb5a9b106b32258c8b7eb73 to your computer and use it in GitHub Desktop.
Generate random BigInt values in the browser of variable bit length
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Returns a random hex string of length chars. */ | |
const randomHexString = (length: number): string => { | |
return Array.from({ length }, () => Math.round(Math.random() * 0xf).toString(16)).join('') | |
} | |
/** Returns a random BigInt of n bits in length. */ | |
export const randomBigIntN = (n: number): bigint => { | |
return BigInt.asUintN(n, BigInt(`0x${randomHexString(Math.ceil(n / 4))}`)) | |
} | |
/** Returns a uniformly distributed 32-bit unsigned integer. */ | |
export const randomUint32 = (): number => Number(randomBigIntN(32)) | |
/** Returns a uniformly distributed 64-bit unsigned integer. */ | |
export const randomUint64 = (): bigint => randomBigIntN(64) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment