Skip to content

Instantly share code, notes, and snippets.

@missinglink
Created July 23, 2024 22:44
Show Gist options
  • Save missinglink/7e52209febb5a9b106b32258c8b7eb73 to your computer and use it in GitHub Desktop.
Save missinglink/7e52209febb5a9b106b32258c8b7eb73 to your computer and use it in GitHub Desktop.
Generate random BigInt values in the browser of variable bit length
/** 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