13

Looking at the various random functions in the standard library, there isn't a way to generate numbers of n-bit length long.

Is there any efficient function I can use to accomplish this?

Ayrx
  • 2,092
  • 5
  • 26
  • 34

2 Answers2

16
>>> import random
>>> random.getrandbits(10)
688L
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • 2
    D'oh how did I miss that one...... – Ayrx May 11 '13 at 11:49
  • I think the result is not exactly `n-bit`. – Lisbeth Mar 06 '20 at 10:02
  • @Lisbeth what do you mean? – jamylak Mar 06 '20 at 11:17
  • try this: print [len(bin(a)[2:]) for a in [random.getrandbits(100) for _ in range(10)]] – Lisbeth Mar 06 '20 at 12:17
  • The correct one is: `print [len(bin(a)[2:]) for a in [getRandomNBitInteger(100) for _ in range(10)]]` – Lisbeth Mar 06 '20 at 12:18
  • @jamylak Please see here: https://asciinema.org/a/y9VVZV0ExLdDmnNXBkyojcUXv – Lisbeth Mar 12 '20 at 18:48
  • @Lisbeth Okay i see what you are trying to say now. However this result is `n-bit`, the reason why you could do `len(bin(688L))` and it says `12` is because it is represented as a `long` and the initial bits are all `0`s therefore they won't show in the `bin` representation. It could be any number up to `n-bit` length so `random.getrandbits(2))` could be `0`, `1`, or `2` or `3`. 0 would be `0b0` which is equivalent to `0b00`, 1 would be `0b1` equivalent to `0b01` and 2, `0b10` and 3, `0b11` they are still all `n-bit` numbers where `n` = 2 although they don't show the initial `0`s in `bin` rep – jamylak Mar 13 '20 at 00:34
  • @Lisbeth I looked up your function and it returns a number in range `2**(N-1) and (2**N)-1.` which I understand is a different definition of it being only the numbers that would take up `N-bit` without including initial `0` bits. https://pythonhosted.org/pycrypto/Crypto.Util.number-module.html#getRandomNBitInteger – jamylak Mar 13 '20 at 00:37
10

Yes there is:

>>> import random
>>> random.getrandbits(1)
0L
>>> random.getrandbits(100)
31456252575598781139680104123L
>>> help(random.getrandbits)
Help on built-in function getrandbits:

getrandbits(...)
    getrandbits(k) -> x.  Generates a long int with k random bits.

From the docs:

random.getrandbits(k)
Returns a python long int with k random bits. This method is supplied with the MersenneTwister generator and some other generators may also provide it as an optional part of the API. When available, getrandbits() enables randrange() to handle arbitrarily large ranges.

pradyunsg
  • 18,287
  • 11
  • 43
  • 96