简体   繁体   中英

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

I can write -1 to the buffer by writeIntBE , the code is:

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

However, the following code is not functional

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

The error code is :

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

Help me understanding the difference, please.

This can be solved by examining the source at:

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

We can see the call to checkInt:

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

Working out the Math.pow's, we see the min is -128 and the max is 127. If we evaluate 0xff alone in the console, we see that is positive 255, which is out of range.

So hexadecimal constants are always positive. I'm sure you can find this in the JavaScript standard. Whereas, you're using the signed version of the call. You can have explicit negative hexadecimal values in JavaScript, which looks freaking odd in my opinion, but that would be -0x1 in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM