我可以通过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
,我们会看到它正 255,超出范围。
所以十六进制常量总是正数。我确信您可以在 JavaScript 标准中找到这一点。然而,您正在使用通话的签名版本。在 JavaScript 中可以有显式的负十六进制值,在我看来这看起来很奇怪,但在本例中是 -0x1
。
关于javascript - Node.js:无法通过 '0xff' 设置值 'buf.writeIntBE()',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32857390/