Could anybody send me any idea to have a sequence of 8bit random numbers?
My idea was to start from a SEED and every fix period (timer interrupt routine) update this number obtaing a pseudo random sequence.
I found some example about "how to generate a stream of bits" or "how to generate a single number", but I've not find, yet, a routine to create a stream of 8bit numbers, and I don't know the theory of RNG.
Any C source code example or alghorithm is welcome.
Thank you in advance. Paolo
Here is simple implementation from one of my previous projects:
Code:
U16 RND_Num; // Current random number
// Initialize random number generator
void SRV_InitRnd(void) {
RND_Num=12345; // Here is initial seed comes
}
// Returns random number from 0 to (max-1)
U16 SRV_Rnd(U16 max) {
U16 i,j;
i=RND_Num>>8;
j=RND_Num&0xFF;
i=i*18273+j;
j=j*29379+i;
RND_Num=((i&0xFF)<<8)|(j&0xFF);
return (RND_Num%max);
}
I cannot try this routine due to MCU limitation (8bit holtek MCU), but I wonder if the same function should be applied to an 8 bit random number.
So, splitting the random byte into 2 nibbles which should be multiplied by little numbers, then shifted and ORed forming the new random number.
Now, I'm using this function, but I don't know how good is the sequence generated by this algorithm, because it is absolutely casual (written by me, which don't know anything about coding.
Code:
void random_next() {
// shift random left, and put b0(n+1)=b4(n)^b7(n)
randomtmp=0;
if (random&0x10) { // extract bit 4
randomtmp++;
}
// randomtmp==1 if bit4 of random ==1
_c=0; // _c is the carry
_rlc(&random); // rotate left through carry
if (_c) randomtmp^=1;
random^=randomtmp;
}
There is a lot of implementation to generate pseudorandom numbers implementin a cellular automata. I want to help you but i donot remmeber how to make it.
It is actually for 8-bit uC (8051) - usually 16-bits numbers are automatically handled by C compiler for uC. To get 8-bit number you can just get the last 8 bits of 16-bits PRN.
psubiaco said:
Now, I'm using this function, but I don't know how good is the sequence generated by this algorithm, because it is absolutely casual (written by me, which don't know anything about coding.