Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a number of n-bit in length using python? [duplicate]

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?

like image 375
Ayrx Avatar asked May 11 '13 11:05

Ayrx


People also ask

How do you generate an N digit random number in Python?

To generate random number in Python, randint() function is used. This function is defined in random module.

How do you generate a random number in a specific range in Python?

Use randint() Generate random integer randint() function to get a random integer number from the inclusive range. For example, random. randint(0, 10) will return a random number from [0, 1, 2, 3, 4, 5, 6, 7, 8 ,9, 10].

How do you generate n random points in Python?

The function randint() generates random integers for you. If you call the function, it returns a random integer N such that a <= N <= b . The randint() method to generates a whole number (integer). You can use randint(0,50) to generate a random number between 0 and 50.


1 Answers

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.

like image 144
pradyunsg Avatar answered Oct 26 '22 23:10

pradyunsg