From a3df2079347a2f78356b54fb89ca7cef13518b2c Mon Sep 17 00:00:00 2001 From: Damien George Date: Sun, 30 May 2021 16:04:17 +1000 Subject: [PATCH] python-stdlib/random: Add getrandbits with no limit on number of bits. Thanks to Macarthur Inbody aka @133794m3r for the implementation. Signed-off-by: Damien George --- python-stdlib/random/random.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/python-stdlib/random/random.py b/python-stdlib/random/random.py index 6a0fed6f..f1d30745 100644 --- a/python-stdlib/random/random.py +++ b/python-stdlib/random/random.py @@ -1,5 +1,20 @@ from urandom import * +_getrandbits32 = getrandbits + + +def getrandbits(bits: int) -> int: + n = bits // 32 + d = 0 + for i in range(n): + d |= _getrandbits32(32) << (i * 32) + + r = bits % 32 + if r >= 1: + d |= _getrandbits32(r) << (n * 32) + + return d + def randrange(start, stop=None): if stop is None: