buffer: fix writeInt{B,L}E for some neg values

The algorithm used to convert negative values to hex generates incorrect
values when the low byte(s) of the value are zero because a carried
subtraction is applied prematurely.

Fixes: https://github.com/nodejs/node/issues/3992
PR-URL: https://github.com/nodejs/node/pull/3994
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
Signed-off-by: Peter A. Bigot <pab@pabigot.com>
This commit is contained in:
Peter A. Bigot 2015-11-23 16:12:46 -06:00 committed by Trevor Norris
parent e5d97fd91a
commit bea67422df
2 changed files with 40 additions and 4 deletions

View file

@ -939,10 +939,13 @@ Buffer.prototype.writeIntLE = function(value, offset, byteLength, noAssert) {
var i = 0;
var mul = 1;
var sub = value < 0 ? 1 : 0;
var sub = 0;
this[offset] = value;
while (++i < byteLength && (mul *= 0x100))
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0)
sub = 1;
this[offset + i] = ((value / mul) >> 0) - sub;
}
return offset + byteLength;
};
@ -962,10 +965,13 @@ Buffer.prototype.writeIntBE = function(value, offset, byteLength, noAssert) {
var i = byteLength - 1;
var mul = 1;
var sub = value < 0 ? 1 : 0;
var sub = 0;
this[offset + i] = value;
while (--i >= 0 && (mul *= 0x100))
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0)
sub = 1;
this[offset + i] = ((value / mul) >> 0) - sub;
}
return offset + byteLength;
};