Generate Random Number in C: XOR Shift Explained

How-to basics · Updated November 23, 2026

To generate a random number in C using XOR, you typically implement an XORShift pseudorandom number generator (PRNG), which uses bitwise XOR and shift operations on a state variable. A minimal example: uint32_t x = 12345; x ^= x << 13; x ^= x >> 17; x ^= x << 5; return x; — this produces a sequence of seemingly random 32-bit numbers.

Why XOR for Randomness?

XOR (exclusive OR) is a fundamental bitwise operation that, when combined with left and right shifts, creates a chaotic mixing of bits. The XORShift family, introduced by George Marsaglia in 2003, exploits the fact that certain combinations of shifts and XORs produce a maximal-period sequence for a given state size. Unlike linear congruential generators (LCGs), XORShift generators are fast, use only integer operations, and have no multiplication or division, making them ideal for embedded systems or performance-critical code.

The core idea: each bit of the state is influenced by bits from other positions, and the XOR operation ensures that the output is not trivially predictable. The sequence repeats after 2^32 - 1 steps for a 32-bit state (excluding zero), which is sufficient for many non-cryptographic uses.

How XORShift Works: Step-by-Step

The classic 32-bit XORShift algorithm uses three operations on a single unsigned integer state:

  1. Left shift and XOR: state ^= state << 13; — shifts bits left and XORs with original, spreading high bits into lower positions.
  2. Right shift and XOR: state ^= state >> 17; — shifts bits right and XORs, mixing low bits into higher positions.
  3. Left shift and XOR again: state ^= state << 5; — final mixing to break correlations.

Each step modifies the state in place. The chosen shift amounts (13, 17, 5) are not arbitrary; they are part of a known good triple that yields a full period. After each call, the function returns the current state value. To get a random number in a range, you typically take the modulo or use scaling, but beware of modulo bias (see below).

Writing a Complete C Function

Here is a complete, reusable XORShift function with a seed initializer:

#include <stdint.h>

static uint32_t xorshift_state = 2463534242; // any non-zero seed

uint32_t xorshift32(void) {
    uint32_t x = xorshift_state;
    x ^= x << 13;
    x ^= x >> 17;
    x ^= x << 5;
    xorshift_state = x;
    return x;
}

void seed_xorshift(uint32_t seed) {
    if (seed == 0) seed = 1; // avoid zero state
    xorshift_state = seed;
}

To generate an integer between 0 and N-1, use xorshift32() % N, but note the modulo bias. For a uniform distribution without bias, use rejection sampling: uint32_t limit = UINT32_MAX - (UINT32_MAX % N); do { r = xorshift32(); } while (r >= limit); return r % N;

Choosing Seed and State Size

The seed must be non-zero; a zero state will always produce zero. Any non-zero 32-bit seed works, but common practice is to use the system time or clock() for varied sequences. For example: seed_xorshift((uint32_t)time(NULL)); — include <time.h>.

State size determines the period and quality. 32-bit XORShift has a period of 2^32-1, which is short for modern simulations. For better quality, use 64-bit or 128-bit variants. A 64-bit XORShift (using uint64_t) with shifts 13, 7, 17 has a period of 2^64-1. For even higher quality, consider the xorshift128+ or xorshift1024* variants, which pass more statistical tests but are more complex.

Common Problems and Pitfalls

  • Zero state: If the state becomes zero, the generator gets stuck at zero forever. Always ensure seed is non-zero and avoid shifts that could zero out.
  • Modulo bias: Using % N when N does not divide 2^32 gives some numbers a slightly higher probability. Use rejection sampling for critical applications.
  • Poor statistical quality: Basic XORShift fails some tests like the diehard suite. For simulations, use a well-tested generator like PCG or Mersenne Twister.
  • Not cryptographically secure: XORShift is predictable; given a few outputs, an attacker can recover the state. Never use it for passwords, tokens, or security.
  • Thread safety: The static state is not thread-safe. Use thread-local storage or mutex if multiple threads call the generator.

XORShift vs. Other C Random Functions

The C standard library provides rand() and srand(), which are simple but often have poor quality and are implementation-defined. XORShift is faster and has a longer period, but rand() is portable and simpler. For modern C, the random() function (POSIX) is better than rand() but still not great. For high-quality randomness, use the PCG family or the Mersenne Twister (e.g., mt19937 in C++). XORShift is a good middle ground: fast, simple, and adequate for games, tests, and non-critical simulations.

Performance and Cost Considerations

XORShift is extremely fast: each call involves only three XORs and three shifts, typically a few CPU cycles. In contrast, rand() often uses a multiplication and modulo, which are slower. There is no memory cost beyond the state variable. For embedded systems with limited resources, XORShift is an excellent choice. However, for applications requiring millions of random numbers per second, even faster generators like xorshift128+ exist, but the difference is negligible on modern hardware.

Safety and When Not to Use XORShift

XORShift is not suitable for cryptographic purposes. If you need secure random numbers, use the operating system's CSPRNG: on Windows, BCryptGenRandom; on Linux, getrandom() or read from /dev/urandom. Also, do not use XORShift for Monte Carlo simulations that require high statistical quality, as it may exhibit correlations. For such cases, use a well-vetted generator like PCG or the Mersenne Twister. Always document the PRNG used, as reproducibility is often required in scientific work.

Frequently Asked Questions

Can I use XORShift for a password generator?

No. XORShift is predictable; an attacker who observes a few outputs can reconstruct the state and predict future numbers. Use a cryptographically secure random number generator from the OS for passwords, tokens, or any security-sensitive data.

What is the period of a 32-bit XORShift?

The period is 2^32 - 1, meaning it generates 4,294,967,295 numbers before repeating. This is because the state never becomes zero, and the transformation is a bijection on the set of non-zero 32-bit integers.

How do I get a random float between 0 and 1?

Cast the 32-bit output to a float and divide by UINT32_MAX: float r = (float)xorshift32() / (float)UINT32_MAX;. Note that this gives a resolution of about 1/4 billion, which is sufficient for most uses.

Why does my XORShift always return the same number?

If you initialize the state to zero, or if your seed is zero, the generator will always return zero. Also, if you call the function without reseeding, it will produce the same sequence every run. Use a time-based seed or a random seed from the OS.

Is XORShift better than rand()?

XORShift is generally faster and has a longer period than the typical rand() implementation, but quality varies. On many systems, rand() uses an LCG with a short period and poor randomness. XORShift is a better choice for most non-cryptographic uses, but for portability, rand() is standard.

Can I make XORShift thread-safe?

Yes, use a thread-local state variable: static _Thread_local uint32_t state; in C11, or use a mutex around the function. Each thread then has its own sequence, avoiding data races.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.