Node.js: 'buf.writeIntBE()' 无法设置值“0xff”

Node.js: Cannot set a value '0xff' by 'buf.writeIntBE()'

我可以通过writeIntBE-1写入缓冲区,代码为:

var b = new Buffer(1);
b.writeIntBE(-1, 0, 1);
console.log(b);
//<Buffer ff>

但是,以下代码不起作用

var b = new Buffer(1);
b.writeIntBE(0xff, 0, 1);
console.log(b);

错误代码是:

buffer.js:794
    throw new TypeError('value is out of bounds');
    ^

TypeError: value is out of bounds
    at checkInt (buffer.js:794:11)
    at Buffer.writeIntBE (buffer.js:919:5)
    at Object.<anonymous> (/home/liuzeya/http/examples/buffer.js:2:3)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:475:10)
    at startup (node.js:117:18)
    at node.js:951:3

请帮我理解其中的区别。

这可以通过检查来源来解决:

https://github.com/nodejs/node/blob/0a329d2d1f6bce2410d65ecd47175b5a4e1c1c91/lib/buffer.js

我们可以看到对 checkInt 的调用:

checkInt(this,
         value,
         offset,
         byteLength,
         Math.pow(2, 8 * byteLength - 1) - 1,
         -Math.pow(2, 8 * byteLength - 1));

计算出 Math.pow,我们看到最小值为 -128,最大值为 127。如果我们在控制台中单独计算 0xff,我们会看到 positive 255,超出范围。

所以十六进制常量总是正数。我相信您可以在 JavaScript 标准中找到它。而您使用的是 signed 版本的调用。你可以在 JavaScript 中有明确的负十六进制值,在我看来这看起来很奇怪,但在这种情况下会是 -0x1