11.10 Getting Random Integers

11.10.1 Problem

Given a pseudo-random number generation interface that returns an array of bytes, you need to get random values in the various integer data types.

11.10.2 Solution

For dealing with an integer that can contain any value, you may simply write bytes directly into every byte of the integer.

11.10.3 Discussion

Do not use this solution for getting random floating-point values; it will not produce numbers in a uniform distribution because of the mechanics of floating-point formats.

To get a random integer value, all you need to do is fill the bytes of the integer with random data. You can do this by casting a pointer to an integer to a binary string, then passing it on to a function that fills a buffer with random bytes. For example, use the following function to get a random unsigned integer, using the spc_rand( ) interface defined in Recipe 11.2:

unsigned int spc_rand_uint(void) {
  unsigned int res;
  spc_rand((unsigned char *)&res, sizeof(unsigned int));
  return res;

This solution can easily be adapted to other integer data types simply by changing all the instances of unsigned int to the appropriate type.

11.10.4 See Also

Recipe 11.2