// maximum for n is 31 or 32 // (32 works but makes things a bit funky because you'll see negative // integers as value, step count and cycle length. Unless you call the // ...AsLong methods.) // TODO: find tap tables for n=25 through 32 // (so for now max is 24) sclass LSFR { // params int n; // max 32 int start = 1; // calculated int tap, cycleLength; // = 2^n-1 // changing variables int step, value; // tap bit mask for different n's (2 through 24) static final int[] tapTable = { 0x3, 0x6, 0xC, 0x14, 0x30, 0x60, 0xB4, 0x110, 0x240, 0x500, 0xE08, 0x1C80, 0x3802, 0x6000, 0xD008, 0x12000, 0x20400, 0x72000, 0x90000, 0x140000, 0x300000, 0x420000, 0xE10000 }; *(int *n) { assertBetween(2, 24, n); cycleLength = (1 << n)-1; tap = tapTable[n-2]; } int next() { if (++step == cycleLength) step = 0; int tapped = countBits(value & tap) & 1; ret value = (value >>> 1) | (tapped << n); } long nextLong() { ret uintToLong(next()); } }