如何识别node.js Buffer

时间:2016-01-08 08:43:32

标签: javascript node.js

假设我想为数组[-1, 255, 3, 4]

创建node.js缓冲区
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 ] }

有没有办法区分负数和正数?

1 个答案:

答案 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