Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++: Fastest way to fill a buffer with random bytes

Tags:

I have this big char array that needs to filled with random bytes in high freq. I wonder if there is any faster way other than the naive way (using for loop - fill each cell with random byte) to do this. There is no requirement on the random quality of the values. Any "random" junk will do. Platform is windows

like image 891
GabiMe Avatar asked Sep 15 '11 08:09

GabiMe


1 Answers

True random (Unix only):

int fd = open("/dev/random", O_RDONLY); read(fd, your_buffer, buffer_size); 

Not completely random (Unix only):

int fd = open("/dev/urandom", O_RDONLY); read(fd, your_buffer, buffer_size); 

Constant random (unless you use srand(time(NULL)), portable):

for(size_t i = 0; i < buffer_size; i++)     your_buffer[i] = rand() % 256; 

Or something like:

memcpy(your_buffer, (void*)memcpy, buffer_size); 
like image 72
wormsparty Avatar answered Oct 14 '22 10:10

wormsparty