How to generate Random N bit hex numbers?

Christ Schlacta aarcane at gmail.com
Mon Apr 19 18:44:53 CEST 2010


any random class that can create an integer can create an n-bit random 
integer.  just create a random number by whatever means, then pull/mask 
off N bits using bitwise operators, and store them however you need.

my_6_bit_rand = rand() & 0x3F; /* 0x3f = 11 1111, so it takes the low 6 
bits of the return from rand, and assigns it to my_6_bit_rand.  you
  can convert it to a hex string using sprintf or display it as hex 
using cout or printf, or you can pull out a C++ string using 
ostringstream et al.

Ali Sydney wrote:
> All,
>     I am rather new to the GMP. With this said, I am attempting to generate a random N bit (where N can be any integer ex. 1024) hexadecimal number using the c++ interface.  Below is a simple test where I generate a random '6' bit number in decimal.  
> 
> gmp_randclass r (gmp_randinit_lc_2exp_size, 32);
> mpz_class z; 
> z=r.get_z_bits(6);  //z stores value of random integer.
> 
> However, I have not been able to find a function to do this similar process and produce hexadecimal random number.  
> 
> If this is not possible, how would I go about converting an mpz_class integer to hexadecimal? For example if
> 
> mpz_class z;
> z=10;
> 
> how would I then convert z to hexadecimal?
> 
> Best Regards,
> Ali
> 
> _______________________________________________
> gmp-discuss mailing list
> gmp-discuss at gmplib.org
> https://gmplib.org/mailman/listinfo/gmp-discuss


More information about the gmp-discuss mailing list