My friend gave me a bit of code for my SDL program, all I know that it makes a random color but I have no idea how it works , here is the code
int unsigned temp = 10101;//seed
for(int y = 0;y < times;y++){
temp = temp*(y+y+1);
temp = (temp^(0xffffff))>>2;
//printf("%x\n",temp);
SDL_FillRect(sprite[y],NULL,temp);
SDL_BlitSurface(sprite[y],&paste[y],rScreen(),NULL);
}
My question is , How does this code work and how does it make a random color
Your friend is creating a “random RGB value” ranging from 0x000000 to 0xFFFFFF out of some amateur PRNG he invented.
I’ll explain the code with comments:
This is the so called “seed”. The initial value that will generate the pseudo-random sequence of values.
then we got the for loop:
each round your friend is trying to make complicated multiplications and sums to come up with a new temp value which is divided by 2 (the >>2 in the code above) and then masked with 0xFFFFFFF to get a value in the range of 0x000000 to 0xFFFFFFF (he wrongly used bitwise XOR ^ instead of bitwise AND &)
The resulting value is used as a RGB value for the SDL_FillRect() function.