Home > Blockchain >  I have a random Number Generator that uses a XOR shift algorithm, using a global variable. Is there
I have a random Number Generator that uses a XOR shift algorithm, using a global variable. Is there

Time:01-29

so I built this "Random" number Generator, and it works exactly like its supposed to. But I feel like the use of a Global variable in this way is cursed, and there must be a better way of accomplishing the same thing. Thanks in Advanced.

unsigned int State = 1804289383;
unsigned int get_random_U32_number() {
    unsigned int Number = State;
    Number ^= Number << 13;
    Number ^= Number >> 17;
    Number ^= Number << 5;
    State = Number;
    return Number;
}

Not sure what else to try, I can't use any built like function like rand() for this project.

CodePudding user response:

Another approach, slightly different from @dbush's answer:

unsigned int get_random_U32_number( void ) {
    static unsigned int State = 1804289383;

    unsigned int Number = State;
    Number ^= Number << 13;
    Number ^= Number >> 17;
    Number ^= Number << 5;
    State = Number;
    return Number;
}

The change to get_random_U32_number( void ) makes it explicit that the function takes no arguments.

CodePudding user response:

You can change your function to take the address of the current state variable as a parameter.

unsigned int get_random_U32_number(unsigned int *State) {
    unsigned int Number = *State;
    Number ^= Number << 13;
    Number ^= Number >> 17;
    Number ^= Number << 5;
    *State = Number;
    return Number;
}

This allows the function to be reentrant.

CodePudding user response:

Make it static to reduce its scope to the local file.

// unsigned int State = 1804289383;
static unsigned int State = 1804289383;
  • Related