假设我想为数组[-1, 255, 3, 4]
var i = new Buffer([-1, 255, 3, 4])
对于负数,它只需要两个补码并按原样存储。所以这里:
console.log(i)
<Buffer ff ff 03 04>
此外,
console.log(i.toJSON())
{ type: 'Buffer', data: [ 255, 255, 3, 4 ] }
有没有办法区分负数和正数?
答案 0 :(得分:2)
正如@Amadan在评论中指出的那样,
Buffer
中没有负数。Buffer
中的每个值都是字节 - 无符号8位值。你无法识别那些不存在的东西
从缓冲区读取数据时,有unsigned
方法,例如readUInt8()
;和signed
方法,例如readInt8()
。
> var i = new Buffer([-1, 255, 3, 4])
undefined
> i.readInt8(0)
-1
> i.readInt8(1)
-1
> i.readUInt8(1)
255
> i.readUInt8(0)
255