http://www.velocityreviews.com/forums/(E-Mail Removed) writes:

> On Wednesday, August 7, 2013 5:07:44 AM UTC-4, Guillaume Dargaud wrote:

>> Hello all,

>> any idea on writing a macro to generate a pseudo-random number using all 64

>> bits of a unsigned long long ? [snip]

>> Anybody can think of a more generic solution independent of RAND_MAX ?

>

> Here's an excerpt of what I use for type 'int'. It essentially

> fills in each byte with a random number, since 'RAND_MAX' is

> likely to be larger than UCHAR_MAX. [and takes the absolute

> value to produce a non-negative number] [snip elaboration]
There are two things wrong with this approach:

1. It can generate trap representations. Note that trap

representations may exist even in implementations that use

twos complement and have no padding bits.

2. The possible existence of multiple representations for a

single value make it very difficult to produce a truly

uniform distribution.

A better approach is to generate an appropriate value directly in

unsigned char units, eg

#include <limits.h>

#define INT_BIT /* .. number of bits in INT_MAX .. */

/* This can be done directly from INT_MAX using

the well known IMAX_BITS macro */

int

uniform_nonnegative_int(){

unsigned mask_shift = (CHAR_BIT-1) - (INT_BIT-1) % CHAR_BIT;

unsigned mask = (unsigned char) -1 >> mask_shift;

int r = mask & (unsigned char) rand();

int i = (INT_BIT-1) / CHAR_BIT;

while( i-- > 0 ) r = r << CHAR_BIT + (unsigned char) rand();

return r;

}

Disclaimer: typed in, not compiled.