21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Discussion<br />

Do not use this solution for getting random floating-point values; it<br />

will not produce numbers in a uniform distribution because of the<br />

mechanics of floating-point formats.<br />

To get a random integer value, all you need to do is fill the bytes of the integer with<br />

random data. You can do this by casting a pointer to an integer to a binary string,<br />

then passing it on to a function that fills a buffer with random bytes. For example,<br />

use the following function to get a random unsigned integer, using the spc_rand( )<br />

interface defined in Recipe 11.2:<br />

unsigned int spc_rand_uint(void) {<br />

unsigned int res;<br />

spc_rand((unsigned char *)&res, sizeof(unsigned int));<br />

return res;<br />

}<br />

This solution can easily be adapted to other integer data types simply by changing all<br />

the instances of unsigned int to the appropriate type.<br />

See Also<br />

Recipe 11.2<br />

11.11 Getting a Random Integer in a Range<br />

<strong>Problem</strong><br />

You want to choose a number in a particular range, with each possible value equally<br />

likely. For example, you may be simulating dice rolling and do not want any number<br />

to be more likely to come up than any other. You want all numbers in the range to be<br />

possible values, including both endpoints. That is, if you ask for a number between 1<br />

and 6, you’d like both 1 and 6 to be as likely as 2, 3, 4, or 5.<br />

Solution<br />

There are multiple ways to handle this problem. The most common is the least correct,<br />

and that is to simply reduce a random integer (see Recipe 11.10) modulo the<br />

size of the range and add to the minimum possible value. This can lead to slight<br />

biases in your random numbers, which can sometimes lead to practical attacks,<br />

because it means that some outputs are more likely than others.<br />

We discuss more exact solutions in the next section.<br />

606 | Chapter 11: Random Numbers<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!