16. Spreading Codes: GPS C/A Codes at Compile Time

PySDR’s Detection chapter ends its correlation section with a real-world example: finding GPS satellites in a 10 ms recording made by Daniel Estévez. Each satellite transmits a 1023-chip C/A code, and the receiver correlates the recording against a local copy of each satellite’s code, over a grid of Doppler shifts, until a peak stands out of the noise. PySDR’s script generates the codes with two shift registers written as NumPy loops, then searches 32 satellites, and finds six.

The codes are the interesting part for a C++ chapter. They are fixed forever by the GPS interface specification, IS-GPS-200, so they are textbook compile-time constants, and the specification describes them in three different ways that must agree. In this chapter the compiler generates all 32 codes, checks the three descriptions against each other, and we then use the codes for two things: verifying the famous correlation properties of Gold codes with bit operations, and running PySDR’s acquisition on the same recording, assembled from the building blocks of earlier chapters.

Two Shift Registers

A C/A code is a Gold code: the XOR of two maximal-length sequences produced by 10-stage linear-feedback shift registers, G1 and G2 (IS-GPS-200, section 3.3.2.3). Both start with all ones; on every clock, the register shifts by one, and a new bit computed as the XOR of a few “tap” stages enters at stage 1. G1 uses taps 3 and 10, G2 uses taps 2, 3, 6, 8, 9 and 10. PySDR writes each register as a loop over a NumPy array with np.roll.

In C++ the natural representation of a 10-bit register is a 10-bit integer, and the taps are a list of compile-time constants, which is exactly what a parameter pack is (code/include/cppsdr/gps.hpp):

template <unsigned... Taps>
class lfsr10 {
    static_assert(sizeof...(Taps) >= 2 && ((Taps >= 1 && Taps <= 10) && ...), "stages are 1..10");
public:
    constexpr unsigned stage(unsigned s) const { return (reg_ >> (s - 1)) & 1u; }
    constexpr unsigned output() const { return stage(10); }
    constexpr void clock()
    {
        const unsigned feedback = (stage(Taps) ^ ...);   // C++17 fold expression over the taps
        reg_ = std::uint16_t(((reg_ << 1) | feedback) & 0x3FFu);
    }
private:
    std::uint16_t reg_ = 0x3FF;  // all ones at the start of every code period
};

using g1_register = lfsr10<3, 10>;               // G1: 1 + x^3 + x^10
using g2_register = lfsr10<2, 3, 6, 8, 9, 10>;   // G2: 1 + x^2 + x^3 + x^6 + x^8 + x^9 + x^10

(stage(Taps) ^ ...) is a fold expression: the compiler expands it into stage(2) ^ stage(3) ^ stage(6) ^ ..., one term per tap, with no loop and no array of taps at run time. The static_assert uses a fold over && to reject a tap outside the register. The two register types read like the polynomials in the specification.

One Table, Three Descriptions

What makes each satellite’s code different is how G2 enters the XOR, and IS-GPS-200 describes this in two equivalent ways in its Table 3-Ia. As a delay: satellite 1 uses G2 delayed by 5 chips, satellite 7 by 139 chips, and so on. PySDR’s code uses this column (G2_DELAY). And as two phase-selector taps: satellite 1 XORs stages 2 and 6 of G2, which is what the hardware in the satellite does, because it costs one XOR gate instead of a 1023-bit delay line. As a third, independent check, the table also lists the first 10 chips of every code, in octal.

Three descriptions of the same 32 codes are an invitation to check them against each other. We put all three columns in one constexpr table and let the compiler generate each code both ways:

struct prn_info {
    std::uint8_t tap1, tap2;
    std::uint16_t g2_delay;
    std::uint16_t first10_octal;
};

inline constexpr std::array<prn_info, 32> table_3_1a{{
    {2, 6, 5, 01440},     {3, 7, 6, 01620},     {4, 8, 7, 01710},     {5, 9, 8, 01744},
    ...
}};

constexpr bool table_is_consistent()
{
    for (unsigned prn = 1; prn <= 32; ++prn) {
        const auto a = ca_code_by_delay(prn);
        if (a != ca_code_by_taps(prn)) return false;
        if (first10(a) != table_3_1a[prn - 1].first10_octal) return false;
    }
    return true;
}
static_assert(table_is_consistent(), "delays, taps and first chips of IS-GPS-200 Table 3-Ia agree");

Note the octal literals: 01440 with a leading zero is octal in C++, so the numbers can be copied from the specification exactly as printed. (The same leading zero is also a classic source of bugs when someone writes 010 meaning ten; here it is what we want.)

If any digit in the table is wrong, in any of the three columns, the program does not compile. That is a much stronger statement than “we copied the table carefully”: two independent descriptions and a checksum agree for all 32 satellites. The table then becomes a constant of the program, all 32 codes generated while compiling:

inline constexpr auto ca_codes = [] {
    std::array<chip_sequence, 32> t{};
    for (unsigned prn = 1; prn <= 32; ++prn) t[prn - 1] = ca_code_by_delay(prn);
    return t;
}();

The test compares them with the codes PySDR’s NumPy loops produce: identical, all 32.

The Compiler Has a Budget

The first version of this code did not compile. It re-ran both shift registers, clock by clock, for every satellite inside table_is_consistent(), and Clang stopped with “constexpr evaluation hit maximum step limit; possible infinite loop?”. Compile-time evaluation is interpreted by the compiler, much more slowly than running the same code, and compilers cap it: Clang at about a million evaluation steps by default (adjustable with -fconstexpr-steps), GCC with its own limits (-fconstexpr-ops-limit, -fconstexpr-loop-limit). Rather than raising the limit for every user of the header, we did less work. G1 and G2 are the same for all satellites, so they are generated once. And the tap description does not need a second register: stage \(s\) of a shift register holds now what will come out of stage 10 in \(10-s\) clocks, so the two G2 stages can be read off the G2 output sequence:

constexpr chip_sequence ca_code_by_taps(unsigned prn)
{
    const auto [t1, t2, d, o] = table_3_1a[prn - 1];   // structured binding
    chip_sequence c{};
    for (std::size_t i = 0; i < chips; ++i)
        c[i] = g1[i] ^ g2[(i + 10 - t1) % chips] ^ g2[(i + 10 - t2) % chips];
    return c;
}

The full register-by-register simulation still exists (ca_code_hardware); the compiler checks it for one satellite, and the test runs it for all 32 at run time. The general lesson: compile-time computation is excellent for tables and checks, but it has a budget, and it pays to compute shared intermediate results once, just as it would at run time.

Correlation with XOR and popcount

Why Gold codes? Because of their correlation properties. A code correlated with itself gives 1023 at zero shift. At any other shift, and against any other satellite’s code at any shift, the correlation of a Gold code of length 1023 takes only three values: \(-65\), \(-1\) and \(63\). That is what lets 31 satellites share one frequency and still be separated (CDMA, as PySDR explains). Let’s check that claim for all 32 codes, all pairs and all 1023 shifts: about a million correlations of 1023 chips each.

A chip is one bit, and the correlation of two \(\pm 1\) sequences counts agreements minus disagreements. Disagreements are exactly the positions where the XOR of the two bit patterns is 1. So if we pack the 1023 chips into sixteen 64-bit words, a correlation is sixteen XORs and sixteen population counts:

// agreements - disagreements = N - 2 * differences
constexpr int correlate(packed_code const& a, packed_code const& b)
{
    int differences = 0;
    for (std::size_t k = 0; k < a.w.size(); ++k) differences += std::popcount(a.w[k] ^ b.w[k]);
    return int(chips) - 2 * differences;
}

std::popcount (C++20, <bit>) compiles to the CPU’s population-count instruction (popcnt on x86, NEON’s cnt on ARM). Each step handles 64 chips, which is exactly how hardware correlators for spreading codes work (XNOR gates and an adder tree), and how the bit-level correlations in binarized neural networks are computed. The test performs all 1 047 520 correlations and finds exactly the set \(\{-65, -1, 63\}\); the whole test, acquisition included, runs in about two seconds.

Acquisition on the Real Recording

With the codes in hand, the acquisition itself follows PySDR’s algorithm step by step: for each satellite, upsample its code to 4000 samples per millisecond and keep the conjugate of its spectrum; for each Doppler bin from \(-5\) to \(+5\) kHz, shift the recording, correlate ten 1 ms blocks by FFT, and add up the squared magnitudes; the satellite is detected if the peak of the resulting Doppler-by-code-phase map is at least 14 dB above its mean. In C++ this is one class (code/include/cppsdr/gps_acquisition.hpp) built almost entirely from earlier chapters:

  • The FFT backend from FIR Filters in C++ (an RAII object whose plans are made in the constructor), with a 4000-point FFTW plan. 4000 is not a power of two, and FFTW does not mind.

  • The integer NCO from Oscillators and Frequency Shifting removes each Doppler offset: nco_fixed_lut<10> nco(-2 * pi * doppler / fs).

  • The code spectra for all 32 satellites are computed once in the constructor, like PySDR’s template_signals dictionary.

The correlation map is a two-dimensional array, Doppler bins by code phase. PySDR uses a 2-D NumPy array; in C++23 the corresponding tool is std::mdspan, a multidimensional view over memory that someone else owns:

auto map = std::mdspan(power_.data(), dopplers_.size(), n_);   // rows: Doppler, columns: code phase
...
for (std::size_t i = 0; i < n_; ++i) map[d, i] += std::norm(fft_.time()[i]);

The storage is a single std::vector<float>, allocated once; std::mdspan adds the 2-D indexing (with C++23’s multidimensional operator[]) and nothing else. Finding the peak is std::ranges::max_element over the flat storage, and the row and column follow from the index. Each search returns a small struct with named fields instead of a dictionary:

struct acquisition_result {
    unsigned prn;
    double doppler_hz;
    std::size_t code_phase_samples;
    double code_phase_chips;
    double pmr_db;
    bool detected;
};

On PySDR’s 10 ms recording, the C++ acquisition finds the same six satellites as PySDR’s script, in the same Doppler bins and at the same code phases, with the same peak-to-mean ratios to a tenth of a dB, and makes the same detection decision for all 32 satellites (code/tests/test_gps.cpp runs PySDR’s script output against it):

SV 11  Doppler  +2500 Hz  phase 3274 samples  PMR 14.6 dB
SV 12  Doppler   -500 Hz  phase 3408 samples  PMR 16.4 dB
SV 22  Doppler  +2500 Hz  phase 2182 samples  PMR 14.4 dB
SV 25  Doppler  +1500 Hz  phase 2338 samples  PMR 15.5 dB
SV 31  Doppler  +5000 Hz  phase 1812 samples  PMR 15.9 dB
SV 32  Doppler  +1000 Hz  phase 1339 samples  PMR 16.2 dB

The same codes in VHDL. A GPS receiver in an FPGA generates the C/A code with exactly these two registers, ten flip-flops and a handful of XOR gates each, clocked at the chip rate, and selects the satellite with the two phase-selector taps. The C++ lfsr10 template is a one-to-one model of that hardware; a test bench can compare the VHDL generator’s output with ca_codes chip by chip.

Key Takeaways

  • Shift registers map naturally onto a small integer and a parameter pack of taps; a fold expression computes the feedback with no run-time data structure.

  • When a specification describes the same thing several ways, put all descriptions in one constexpr table and static_assert that they agree. Octal literals let you copy octal tables verbatim.

  • Compile-time evaluation has a budget: compute shared intermediates once, and leave the heaviest checks to the test suite.

  • Correlating binary sequences is XOR plus std::popcount, 64 chips per instruction.

  • std::mdspan gives a 2-D view over one flat buffer, the C++23 counterpart of a 2-D NumPy array, without owning or allocating anything.