简体   繁体   中英

How to recognize negative numbers in node.js Buffer

Suppose say I want to create a node.js Buffer for the array [-1, 255, 3, 4]

var i = new Buffer([-1, 255, 3, 4])

For negative numbers, it will just take two's complement and store it as is. So here:

console.log(i)
<Buffer ff ff 03 04>

Also,

console.log(i.toJSON())
{ type: 'Buffer', data: [ 255, 255, 3, 4 ] }

Is there a way to distinguish negative numbers from positive ones?

As @Amadan point out in the comment,

There is no negative numbers in Buffer . Each value in Buffer is a byte - an unsigned 8-bit value . You can't recognise something that is not there

When read data from buffer, there are unsigned method, such as readUInt8() ; and signed method, such as 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

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