{
  "id": "xorshift",
  "title": "Xorshift",
  "lang": "en",
  "source_lang": "en",
  "summary": "Xorshift is a family of fast pseudorandom number generators that update their state using bitwise exclusive-or and shift operations.",
  "category": "computer-science",
  "subcategory": "algorithms-theory",
  "type": "concept",
  "aliases": [
    "Xorshift generator",
    "XOR-shift generator"
  ],
  "generated_at": "2026-11-05",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/xorshift/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/xorshift/",
      "json": "https://aiwiki.page/zh/xorshift.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "Xorshift is a family of pseudorandom number generators whose internal state is updated through sequences of bitwise exclusive-or (XOR) and shift operations. Introduced by George Marsaglia in 2003, these generators are notable for their small state, simple implementation, and high speed. Their state transitions are linear over the two-element field, which makes their periods mathematically tractable but also creates detectable statistical structure. Later variants add output transformations, such as multiplication or addition, to reduce some of these weaknesses. Neither basic xorshift nor its commonly used scrambled variants are cryptographically secure."
    },
    {
      "heading": "Basic operation",
      "text": "A xorshift generator stores a fixed-size binary state and repeatedly modifies it using operations of the form\n\n\\[x \\leftarrow x \\oplus (x \\ll a)\\]\n\nor\n\n\\[x \\leftarrow x \\oplus (x \\gg b),\\]\n\nwhere \\(\\oplus\\) denotes exclusive-or, \\(\\ll\\) is a left shift, and \\(\\gg\\) is a logical right shift. A logical right shift fills vacated positions with zeros; a fixed-width left shift discards bits shifted beyond the word boundary.\n\nEach operation combines the current state with a displaced copy of itself. A typical one-word generator performs three such operations, alternating shift directions, and returns the resulting state as its next output.\n\nThe following implementation in the C programming language is commonly called xorshift32:\n\n#include <stdint.h>\n\nuint32_t xorshift32(uint32_t *state)\n{\n    uint32_t x = *state;\n    x ^= x << 13;\n    x ^= x >> 17;\n    x ^= x << 5;\n    *state = x;\n    return x;\n}\n\nFor a nonzero initial state, this particular generator has period \\(2^{32}-1\\). An initial state of zero remains zero indefinitely.\n\nThe shifts and their order are part of the generator's definition. Arbitrary replacements for the constants do not necessarily preserve the maximum period or acceptable statistical behavior."
    },
    {
      "heading": "Mathematical structure",
      "text": "Linearity over a binary field\n\nAn \\(n\\)-bit state can be regarded as a vector in the vector space \\(\\mathbb{F}_2^n\\), where \\(\\mathbb{F}_2\\) is the finite field containing zero and one. In this setting, XOR is vector addition, and a fixed shift is a linear transformation.\n\nA complete xorshift update can therefore be represented by a binary matrix \\(T\\):\n\n\\[s_{t+1}=T s_t.\\]\n\nAfter \\(k\\) updates,\n\n\\[s_{t+k}=T^k s_t.\\]\n\nThis structure connects xorshift generators to linear-feedback shift registers. Both generate deterministic sequences through linear recurrences over a binary field, although xorshift implementations organize their work around efficient word-level operations.\n\nInvertibility and maximum period\n\nFor shift distances strictly between zero and the word width, an operation such as \\(x \\leftarrow x \\oplus (x \\ll a)\\) is invertible. The original bits can be recovered progressively from the unchanged end of the word. The corresponding right-shift operation is also invertible.\n\nConsequently, a composition of these operations permutes the state space. Zero is always a fixed point, so the longest possible cycle on the remaining \\(n\\)-bit states has length\n\n\\[P=2^n-1.\\]\n\nNot every invertible transition achieves this period. A standard criterion for a full-period linear transition is that its characteristic polynomial be primitive over \\(\\mathbb{F}_2\\). Suitable shift parameters must therefore be established mathematically or by equivalent period tests.\n\nFor a full-period generator, every nonzero state occurs exactly once per cycle. This is a statement about state coverage, not a guarantee that short output sequences behave like independent random samples.\n\nState size and output size\n\nThe simplest variants use one machine word as both state and output. Other designs maintain several words while returning only one word per update. For example, the classic xorshift128 uses four 32-bit words and can achieve period \\(2^{128}-1\\).\n\nA larger state increases the possible period but does not remove linear dependencies. State size, output width, period, and statistical quality are distinct properties."
    },
    {
      "heading": "History and related families",
      "text": "Marsaglia's 2003 paper, Xorshift RNGs, presented generators based on combinations of shifts and XORs, including single-word and multiword forms. They offered an economical alternative to generators requiring more arithmetic or larger state arrays.\n\nSubsequent work focused on improving statistical behavior without sacrificing the speed of the underlying transition. An important distinction emerged between:\n\n- State transition: the rule that advances the internal state.\n- Output function: the rule that converts a state, or several state words, into the value returned to a program.\n\nA generator can retain a linear state transition while using an output function that is nonlinear over \\(\\mathbb{F}_2\\). This is often called scrambling.\n\nNames such as xorshift32 and xorshift128 do not, by themselves, describe every implementation detail. Shift constants, update order, word arrangement, and output selection are necessary to identify an exact sequence."
    },
    {
      "heading": "Major variants",
      "text": "Plain xorshift\n\nPlain xorshift generators return a state word directly, without a nonlinear output transformation. Their advantages are minimal computation and straightforward implementation.\n\nTheir principal limitation is exposed binary linearity. Statistical tests designed to identify linear relations can distinguish their output from independent random bits, even when the period is very long.\n\nXorshift*\n\nA xorshift* generator multiplies a state-derived word by a fixed odd constant, with arithmetic performed modulo \\(2^w\\) for a \\(w\\)-bit output:\n\n\\[y_t=cx_t \\pmod{2^w}.\\]\n\nAn odd multiplier is invertible modulo \\(2^w\\), so this transformation is a permutation of the possible word values. Carries from multiplication introduce nonlinearity over \\(\\mathbb{F}_2\\), improving many statistical properties.\n\nThe transformation does not eliminate every weakness. In particular, multiplication by an odd constant leaves the least significant bit unchanged:\n\n\\[y_t \\bmod 2=x_t \\bmod 2.\\]\n\nWhen applied to a full-state output, invertible multiplication also does not conceal the state from an observer who knows the generator.\n\nXorshift+\n\nA xorshift+ generator produces its output by adding selected state words modulo \\(2^w\\):\n\n\\[y_t=u_t+v_t \\pmod{2^w}.\\]\n\nThe carry operations introduce binary nonlinearity. Xorshift128+ is a prominent example, combining a 128-bit state with 64-bit outputs.\n\nThe lowest output bit remains the XOR of the corresponding input bits, because no carry enters that position. Addition-based scrambling therefore does not remove all low-bit linear structure.\n\nXORWOW\n\nXORWOW combines a xorshift recurrence with an additive counter, commonly described as a Weyl sequence. The counter advances by a fixed odd increment modulo a power of two and is combined with the xorshift output.\n\nThis construction introduces a separate component into the generator rather than simply applying a stateless transformation to one state word. It has been used in GPU random-number generation.\n\nXoroshiro and xoshiro\n\nXoroshiro and xoshiro are related successor families that use rotations alongside XORs and shifts. Their names refer to the operations used in their state transitions.\n\nThey are not simply alternative parameter sets for the original three-shift recurrence. Different members use different state layouts and output scramblers, including +, ++, and ** forms. Statistical findings about one member do not automatically apply to every other member."
    },
    {
      "heading": "Statistical quality",
      "text": "A long period is necessary for many uses, but it is not sufficient evidence of high-quality randomness. A sequence can visit an enormous number of states while retaining exploitable correlations.\n\nPlain xorshift output is particularly vulnerable to tests involving binary linear algebra, including matrix-rank and linear-complexity tests. These examine whether sampled bits satisfy more linear relations than expected from independent random data.\n\nSuites such as TestU01 assess multiple statistical properties. Results depend on the exact generator, output bits examined, sample size, and how outputs are presented to the tests. Testing a full output word, only its lowest bits, or a bit-reversed version can expose different weaknesses.\n\nScrambling generally improves performance on statistical tests, but it does not establish independence or prove suitability for every simulation. Likewise, passing a finite collection of tests does not establish cryptographic security."
    },
    {
      "heading": "Implementation and reproducibility",
      "text": "Seeding\n\nThe entire xorshift state must not be zero. In a multiword generator, individual words may be zero as long as the complete state satisfies the generator's requirements.\n\nA nonzero seed prevents the absorbing zero state, but does not ensure that closely related seeds give well-separated initial sequences. Larger generators are often initialized using a separate mixing procedure that expands a seed into the required state.\n\nFor reproducible computation, the generator variant, initialization method, output conversion, and state must all be specified.\n\nWord arithmetic\n\nImplementations depend on fixed-width binary operations. Important details include:\n\n- Using unsigned values where logical right shifts are required.\n- Preserving the specified word width.\n- Applying modular arithmetic to multiplication and addition scramblers.\n- Avoiding shift counts outside the language's permitted range.\n\nSigned shifts and integer overflow have language-specific semantics and can make superficially similar implementations behave differently.\n\nConverting outputs\n\nA raw random word is not automatically a uniformly distributed value in an arbitrary interval. Reducing an output modulo \\(m\\) can introduce bias if the source range is not divisible by \\(m\\).\n\nLikewise, converting words into floating-point values requires a defined mapping. Implementations often select high-order bits when forming a binary fraction, but this changes which properties of the underlying output affect the result.\n\nThese conversion issues are separate from the xorshift recurrence itself and also affect other generator families.\n\nParallel streams\n\nBecause the state transition is linear, generators can support jump-ahead operations based on powers of \\(T\\). Such operations advance the state by a large fixed distance without generating every intervening output.\n\nThis is useful in parallel computing, where workers may receive separated portions of a sequence. Different seeds alone do not establish independent streams: for a full-period recurrence, all nonzero states lie on the same cycle. Avoiding overlap requires attention to stream spacing and the number of outputs consumed."
    },
    {
      "heading": "Applications and limitations",
      "text": "Xorshift-based generators are used in simulations, procedural content generation, computer graphics, testing, and randomized algorithms where speed and reproducibility are important. Their compact states can be useful when many generator instances are maintained simultaneously.\n\nSuitability depends on the exact variant and workload. A 32-bit state has fewer than \\(4.3\\) billion nonzero states, making its period short for high-throughput or long-running computations. Larger states address period length, while output scrambling addresses some—but not all—statistical weaknesses.\n\nXorshift generators are unsuitable for cryptographic purposes such as key generation, secret tokens, and unpredictable challenges. In plain variants, outputs can directly expose the state or provide linear equations from which it can be recovered. Common scrambling operations were designed for statistical quality, not resistance to cryptanalysis. Statistical randomness and resistance to prediction by an adversary are different requirements."
    }
  ],
  "links": [
    "pseudorandom-number-generator",
    "exclusive-or",
    "c-programming-language",
    "vector-space",
    "finite-field",
    "matrix",
    "polynomial",
    "graphics-processing-unit",
    "integer-overflow",
    "parallel-computing",
    "computer-graphics",
    "randomized-algorithm",
    "cryptography",
    "cryptanalysis"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}