Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Linear feedback shift registers, m-sequences and Gold codes

ProblemGenerate long, noise-like binary sequences with a few gates: for scramblers, test patterns, spread-spectrum codes and sequences with sharp autocorrelation and low cross-correlation
Devised bySolomon Golomb (1955–67), the theory of shift-register sequences; Robert Gold (1967), families of codes with bounded cross-correlation
AccuracyExact: periods, primitivity and correlation values match the theory (tables below)
CostOne parity and one shift per output bit; the primitivity test needs bit operations plus factoring
Read firstDivisibility and modular arithmetic
APILfsr (new, from_polynomial, step, bits, period), is_primitive_polynomial, maximum_length_polynomial, maximum_length_polynomials, all_maximum_length_polynomials, gold_codes, gold_correlation_bound

Overview

A linear feedback shift register (LFSR) holds bits. At each step it outputs one bit, shifts, and feeds in the XOR of a fixed set of its bits, the taps. Its output obeys a linear recurrence over GF(2), so its behaviour is governed by a polynomial. When the polynomial is primitive, the register runs through all nonzero states before repeating. Its output is then a maximum-length sequence (m-sequence), which is balanced and looks random in many statistical senses. Its autocorrelation is nearly an impulse. Two m-sequences chosen as a preferred pair generate a Gold family of sequences whose cross-correlations are all small, so many users can share a channel.

Where it is used

A few flip-flops and exclusive-ORs generate long pseudo-random bit sequences.

  • GPS and CDMA. Gold codes are the spreading sequences of GPS signals and of 3G cellular systems.
  • Data scrambling and test patterns. Ethernet, USB, SATA and PCIe scramble their data to avoid long runs and spectral lines; BER testers use PRBS sequences.
  • Cyclic redundancy checks. CRC computation is an LFSR division.
  • Built-in self test of chips. Pseudo-random test patterns are generated with LFSRs.

History

Shift-register sequences were studied in the 1950s for radar, missile guidance and cryptography. Solomon Golomb, at the Jet Propulsion Laboratory, developed their theory and published it as Shift Register Sequences (1967). His randomness postulates describe the balance, runs and correlation of m-sequences. JPL used them to range spacecraft, and LFSR scramblers and test patterns (PRBS) appear in nearly every serial link standard. Robert Gold (1967) found the preferred pairs and the families named after him, and Tadao Kasami found related sets. Gold codes became the spreading codes of GPS (the C/A code, from two 10-stage registers) and of W-CDMA.

The idea

The recurrence and its polynomial

A linear feedback shift register (LFSR) is a row of one-bit cells. At each clock tick the bits shift along by one place, the bit that falls off the end is the output, and the vacated cell is filled with the XOR of a fixed selection of the old bits, the taps. It is about the cheapest circuit that can generate a long, random-looking sequence of bits.

In symbols, the library’s register holds bits , with the oldest in bit 0. It outputs and shifts in

the parity of the state ANDed with the tap mask . The characteristic polynomial is . Lfsr::from_polynomial takes it as a bit mask, so 0b1011 is . An example. Take and , so that and the recurrence is . Starting from the bits , the sequence continues

and repeats with period 7. During one period the three-bit state takes each of the seven nonzero values exactly once.

The period. The next state depends only on the current one, and there are finitely many states, so the sequence must eventually repeat. The all-zero state is a fixed point (the XOR of zeros is zero), so it must be avoided, and it cannot occur in a cycle with other states. That leaves nonzero states, so the period is at most . A sequence that achieves this is a maximum-length sequence, or m-sequence. Whether it is achieved depends only on the polynomial. Algebraically, one step of the register is multiplication by modulo , so the period is the order of modulo : the smallest with . The order equals exactly when is a primitive polynomial.

Testing primitivity

of degree is primitive if and for every prime dividing . Then the order is exactly , and is irreducible because its quotient ring has units and so is a field. is_primitive_polynomial computes the powers by square-and-multiply with carry-less arithmetic. It factors by trial division, which limits it to degree 40. There are primitive polynomials of degree . maximum_length_polynomial returns one of minimal weight (fewest taps, the cheapest hardware), the numerically smallest among them:

Table 18.6. Primitive polynomials found against the count .

degree nperiod 2ⁿ − 1primitive polynomials foundφ(2ⁿ − 1)/nminimal-weight choice
2311
3722
41522
53166
66366
71271818
82551616
1010236060
124095144144
166553520482048
2010485752400024000
2416777215276480
31214748364769273666
32429496729567108864

The counts found by all_maximum_length_polynomials agree with the formula.

Properties of m-sequences

Because the state passes through every nonzero value once per period, an m-sequence of period has several properties expected of a random sequence.

  • Balance. It has ones and zeros (the example has four ones and three zeros). The missing zero corresponds to the excluded all-zero state.
  • Windows. Every nonzero pattern of consecutive bits appears exactly once per period.
  • Autocorrelation. Map the bits to and compare the sequence with a cyclically shifted copy of itself, adding up the products. At zero shift every product is and the sum is . At every other shift the agreements and disagreements almost cancel, and the sum is exactly :

Figure 18.4. m-sequence autocorrelation.

A single sharp peak with a flat floor is the ideal shape for measuring a delay. That makes m-sequences ideal for ranging and channel sounding: a correlator finds the delay unambiguously.

Gold codes

Systems in which many transmitters share a channel, such as satellite navigation, give each one its own code and separate them by correlation. That needs a large family of sequences in which every pair has low cross-correlation, at every shift. Two m-sequences of the same length can still cross-correlate strongly. Gold showed that if is the decimation with , where for odd or for , then and are a preferred pair. Their cross-correlation takes only the three values , and , with . The family of all shifts keeps the same three values between any two members. gold_codes uses () for odd and () for . No family exists when .

Over all shifts between the first 12 codes and every other member of the family for , the cross-correlation takes only the values -17, -1, 15 (the theory: , and ), with counts 40624, 93922, 52144. Pairing the first m-sequence with another of the same length, chosen badly ( with ), gives cross-correlations as large as 41.

Algorithm

One step of the register, with the state held in an integer of bits:

  1. the output is bit 0 of the state;
  2. the feedback bit is the parity of the state ANDed with the tap mask (the XOR of the tapped bits);
  3. shift the state right by one, and place the feedback bit in bit .

Testing whether a polynomial of degree is primitive.

  1. Factor into primes by trial division.
  2. Compute by square-and-multiply, in arithmetic on polynomials with coefficients modulo 2 (shifts and XORs). If the result is not 1, the polynomial is not primitive.
  3. For each prime factor , compute . If any is 1, the order of is a proper divisor of , and the polynomial is not primitive.
  4. Otherwise it is primitive.

Finding a maximum-length polynomial: try the polynomials of degree in order of increasing number of terms, and within that in increasing numerical order, and return the first that is primitive.

A Gold family for degree .

  1. Generate one period, bits, of the m-sequence from the minimal-weight primitive polynomial.
  2. Form by decimation: , with for odd and for .
  3. The family is , , and the XOR of with each of the cyclic shifts of : sequences.

Implementation

    pub fn step(&mut self) -> u8 {
        let out = (self.state & 1) as u8;
        let fb = ((self.state & self.taps).count_ones() & 1) as u64;
        self.state = (self.state >> 1) | (fb << (self.width - 1));
        out
    }
    let order = (1u64 << n) - 1;
    // x^order must be 1 and x^(order/q) != 1 for every prime q dividing order.
    if pow_mod(2, order, poly) != 1 {
        return false;
    }
    prime_factors(order).into_iter().all(|q| pow_mod(2, order / q, poly) != 1)
    let q = if n % 2 == 1 { 3 } else { 5 };
    let v: Vec<u8> = (0..period).map(|t| u[(q * t) % period]).collect();
    let mut family = Vec::with_capacity(period + 2);
    family.push(u.clone());
    family.push(v.clone());
    for shift in 0..period {
        family.push((0..period).map(|t| u[t] ^ v[(t + shift) % period]).collect());
    }
  • Lfsr is an Iterator over its output bits, up to 64 stages wide.
  • Gold codes are returned as 0/1 bits; map them to chips with .
  • The table of minimal-weight polynomials (degrees 2–32) is computed once, on first use.

In practice

//! Linear feedback shift registers, primitive polynomials and Gold codes.

use lib_jsl_information::lfsr::{Lfsr, gold_codes, gold_correlation_bound, is_primitive_polynomial, maximum_length_polynomial};

fn main() {
    // x^4 + x + 1 is primitive: the register visits all 15 nonzero states.
    let mut r = Lfsr::from_polynomial(0b10011, 0b0001);
    println!("x^4 + x + 1: period {:?}, bits {:?}", r.period(100), r.bits(15));
    // x^4 + x^3 + x^2 + x + 1 is irreducible but not primitive: x^5 = 1, so the period is 5.
    println!("x^4 + x^3 + x^2 + x + 1: primitive {}, period {:?}", is_primitive_polynomial(0b11111), Lfsr::from_polynomial(0b11111, 1).period(100));
    println!("degree-16 maximum-length polynomial: {:#x}", maximum_length_polynomial(16).unwrap());
    let family = gold_codes(5).unwrap();
    let chips = |s: &[u8]| s.iter().map(|&b| 1 - 2 * b as i32).collect::<Vec<i32>>();
    let (a, b) = (chips(&family[2]), chips(&family[7]));
    let mut values: Vec<i32> = (0..31).map(|s| (0..31).map(|t| a[t] * b[(t + s) % 31]).sum()).collect();
    values.sort();
    values.dedup();
    println!("{} Gold codes of length {}; cross-correlation values {values:?} (bound t(5) = {})", family.len(), family[0].len(), gold_correlation_bound(5).unwrap());
}
x^4 + x + 1: period Some(15), bits [1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1]
x^4 + x^3 + x^2 + x + 1: primitive false, period Some(5)
degree-16 maximum-length polynomial: 0x1002d
33 Gold codes of length 31; cross-correlation values [-9, -1, 7] (bound t(5) = 9)

The second polynomial divides , so although it is irreducible its period is only 5.

Strengths

  • Very cheap generators with exactly known period and correlation; Gold families give many nearly orthogonal codes.

Weaknesses

  • Linear, so useless for cryptography on their own: output bits reveal the whole register (Berlekamp-Massey).
  • Primitivity testing is limited to degree 40 by trial-division factoring.

Exercises

  1. Show that the output of an LFSR from a nonzero state is periodic, and that its period divides the order of modulo .
  2. Prove that an m-sequence has ones per period.
  3. Derive the two-valued autocorrelation from the shift-and-add property: is a shift of .
  4. Verify for by listing the primitive polynomials.
  5. Use the Berlekamp-Massey algorithm to recover the polynomial of the example’s register from 8 output bits.
Hints and answers
  1. The state evolves by multiplication by modulo in , so it is periodic, and the sequence repeats after steps if (for a nonzero state); the period divides the order of modulo .
  2. In a period of steps every nonzero -bit state occurs exactly once, and exactly of those states have the output bit equal to 1.
  3. is a nonzero m-sequence satisfying the same recurrence, hence a shift of . Over one period the agreements minus disagreements of and are therefore , so the autocorrelation is for and at .
  4. The number of primitive polynomials of degree is : for and for .
  5. From output bits, Berlekamp-Massey finds the shortest LFSR that generates them; with a register of length , bits suffice, so 8 bits recover a register of up to 4 stages.

Further reading

  • S. W. Golomb, Shift Register Sequences, Holden-Day, 1967; 3rd ed., World Scientific, 2017.
  • R. Gold, “Optimal binary sequences for spread spectrum multiplexing”, IEEE Transactions on Information Theory 13 (1967) 619–621.
  • D. V. Sarwate and M. B. Pursley, “Crosscorrelation properties of pseudorandom and related sequences”, Proceedings of the IEEE 68 (1980) 593–619.
  • R. Lidl and H. Niederreiter, Finite Fields, 2nd ed., Cambridge University Press, 1997, chapters 3 and 8.