How to generate a number of n-bits in length using python?

Considering various random functions in the standard library, there is no way to generate numbers of length n bits.

Is there any efficient feature that I can use for this?

+4
source share
2 answers
>>> import random >>> random.getrandbits(10) 688L 
+5
source

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 long python int with k random bits. This method comes with a MersenneTwister generator, and some other generators may also provide it as an optional part of the API. When available, getrandbits() allows randrange() handle arbitrarily large ranges.

+6
source

Source: https://habr.com/ru/post/1480230/


All Articles