[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 243
  • Last Modified:

random byte 0-6

I want to randomly pick a byte from 0 to 6 not sure how to do this.
0
WackoMike
Asked:
WackoMike
2 Solutions
 
jkrCommented:
You could use

#include <stdlib.h>
#include <stdio.h>
#include <time.h>


typedef unsigned char BYTE;

BYTE RandomByteFrom0To6() {

    int i = rand() * 6 / RAND_MAX; // create a random number and map it to the range 0-6

    return (BYTE) i;
}

and call it like

int main( void )
{
   BYTE i;

   /* Seed the random-number generator with current time so that
    * the numbers will be different every time we run.
    */
   srand( (unsigned)time( NULL ) );

   /* Display 10 numbers. */
   for( i = 0;   i < 10;i++ )
      printf( "  %1.1d\n", RandomByteFrom0To6() );

   return 0;
}
0
 
Jaime OlivaresCommented:

int main()
{
   int randomnum;
 
   srand(time(NULL));

   // Do work here that uses rand(), for example
   for (int i= 0; i< 10; i++)
   {
     randomnum = rand() % 7;
     printf("%i\n\r", randomnum);
   }

   return 0;
}
0
 
Jaime OlivaresCommented:
oops! a minute later.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
NievergeltCommented:
Yes jaime, but your example should work.
0
 
Jaime OlivaresCommented:
You will need some headers, here is a fully tested code:

#include <stdio.h>
#include <time.h>
#include <math.h>
#include <stdlib.h>

int main()
{
   int randomnum;
 
   srand(time(NULL));

   // Do work here that uses rand(), for example
   for (int i= 0; i< 10; i++)
   {
     randomnum = rand() % 7;
     printf("%i\n\r", randomnum);
   }

   return 0;
}
0
 
jkrCommented:
>> Yes jaime, but your example should work.

Both will work.
0
 
WackoMikeAuthor Commented:
since you both answer so quick i gave you both 250 i hope that is ok with you guys. Thanks for the help!
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now