Frequently Asked Questions

How can I generate a random number?

Posted by PCM Programmer on the user forums, May 26th 2000.

To create a random number, we calculate the parity on a byte that has been ANDed with 0xb4. We then shift that parity bit into the LSB of the byte.

Editors comments: In this example, rand() generates the random number and srand() sets the seed. The seed is a global variable and defined by 'random_byte'. This isn't perfect, but it works. With some modification, you could drop the srand() function and pass the seed value as a paramater to rand().

Another thought is to seed the random number generator with a counter from one of the timers. Timer 2 may be more ideal since it is 16bits, therefore resulting in less repetition or patterns appearing in the numbers generated. However, this example only uses 8 bit bytes for random number generation so you will have to edit it for a 16bit seed for full effect.

char random_byte;

char rand(void)   {
   char sum;
   sum = 0;
   // This calculates parity on the selected bits (mask = 0xb4).
   if(random_byte & 0x80)
      sum = 1;
   if(random_byte & 0x20)
      sum ^= 1;
   if(random_byte & 0x10)
      sum ^= 1;
   if(random_byte & 0x04)
      sum ^= 1;
   random_byte <<= 1;
   random_byte |= sum;

void srand(char seed) {
   random_byte = seed;

C-Aware IDE Demo
Embedded C Learners Kit
EZ App Lynx