Generating random unsigned char values in C++

c++, random, unsigned-char

Solution

A lot faster will be simple

unsigned char a = (unsigned char) rand();

Or you can do even 4 shifts of generated integer (on 32bit architecture) to four times reduce call to `rand()`:

int a = rand();
unsigned char r1 = (unsigned char) a;
unsigned char r2 = (unsigned char) a >> 8;
unsigned char r3 = (unsigned char) a >> 16;
unsigned char r4 = (unsigned char) a >> 24;

Or something like that.

Problem

I was wondering how to generate random unsigned char values. My idea; `rand()%255;` since unsigned chars support between 0-255. I was wondering if this method could be improved(or is it the most legit way to do this)

Original source