BigInt Width Helpers Model Register Wrap

BigInt.asUintN and asIntN reinterpret values at a fixed bit width, giving counters and checksum fields the modular wrap hardware registers have.

JavascriptData Integrity

Code

javascriptsnippet
16 lines
// asUintN reinterprets a BigInt as an unsigned width-bit value: it wraps
// modulo 2^width instead of growing
console.log('u8 wrap    :', BigInt.asUintN(8, 255n + 2n));
console.log('u8 from -1 :', BigInt.asUintN(8, -1n));

// asIntN keeps the top bit as the sign instead
console.log('i8 at 128  :', BigInt.asIntN(8, 128n));
console.log('i8 at 127  :', BigInt.asIntN(8, 127n));

// Fixed-width register and checksum fields wrap exactly this way
const steps = [200, 100]; // an 8-bit counter receiving 200 then 100
let counter = 0n;
for (const step of steps) {
  counter = BigInt.asUintN(8, counter + BigInt(step));
  console.log('counter:', counter);
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

u8 wrap    : 1n
u8 from -1 : 255n
i8 at 128  : -128n
i8 at 127  : 127n
counter: 200n
counter: 44n

How it works

Repetition is confined to for (const step of steps) — the rest of the file is straight-line.

Top-level bindings steps, counter hold the demo state — nothing sits inside a function scope.

What to watch for

  • Zero-fetch snippet: every identifier resolves inside the language distribution.

Using it

Every run emits labeled lines — u8 wrap :, u8 from -1 :, i8 at 128 : — when the file runs.

Key statements worth quoting

const steps = [200, 100]; // an 8-bit counter receiving 200 then 100
let counter = 0n;
counter = BigInt.asUintN(8, counter + BigInt(step));

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `steps`, `counter`.