← 中文资源

简体中文版本

BigInt 位宽助手模拟寄存器回绕

BigInt.asUintN 按固定位宽做无符号模 2^width 回绕,asIntN 把最高位当符号位;8 位计数器收到 200 再加 100 正确回绕到 44,与硬件寄存器行为一致。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

驱动整个流程的是 for (const step of steps) 这一个循环。 各个操作都建立在顶层绑定之上:steps、counter。

使用要点

  • 直接运行文件,输出会带上标签,比如 u8 from -1 :、counter:——输出的每一行都能指回产生它的那次调用。

常见问题

包管理器会看到什么?

一份空的依赖清单。示例没有需要抓取的导入。 文件用顶层绑定保存自己的状态:steps、counter。

核心语句

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

代码示例

// 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);
}