JavaScript:将 3 个字节的缓冲区作为整数读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30911185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:55:24  来源:igfitidea点击:

JavaScript: reading 3 bytes Buffer as an integer

javascriptnode.jsbuffer

提问by kmachnicki

Let's say I have a hex data stream, which I want to divide into 3-bytes blocks which I need to read as an integer.

假设我有一个十六进制数据流,我想将其分成 3 个字节的块,我需要将其作为整数读取。

For example: given a hex string 01be638119704d4b9aI need to read the first three bytes 01be63and read it as integer 114275. This is what I got:

例如:给定一个十六进制字符串,01be638119704d4b9a我需要读取前三个字节01be63并将其读取为 integer 114275。这是我得到的:

var sample = '01be638119704d4b9a';
var buffer = new Buffer(sample, 'hex');
var bufferChunk = buffer.slice(0, 3);
var decimal = bufferChunk.readUInt32BE(0);

The readUInt32BEworks perfectly for 4-bytes data, but here I obviously get:

readUInt32BE对于 4 字节数据非常有效,但在这里我显然得到:

RangeError: index out of range
  at checkOffset (buffer.js:494:11)
  at Buffer.readUInt32BE (buffer.js:568:5)

How do I read 3-bytes as integer correctly?

如何正确读取 3 个字节作为整数?

回答by mscdex

If you are using node.js v0.12+ or io.js, there is buffer.readUIntBE()which allows a variable number of bytes:

如果您使用的是 node.js v0.12+ 或 io.js,则buffer.readUIntBE()允许可变数量的字节:

var decimal = buffer.readUIntBE(0, 3);

(Note that it's readUIntBEfor Big Endian and readUIntLEfor Little Endian).

(请注意,它readUIntBE适用于 Big Endian 和readUIntLELittle Endian)。

Otherwise if you're on an older version of node, you will have to do it manually (check bounds first of course):

否则,如果您使用的是旧版本的节点,则必须手动执行(当然首先检查边界):

var decimal = (buffer[0] << 16) + (buffer[1] << 8) + buffer[2];

回答by Ernest Okot

I'm using this, if someone knows something wrong with it, please advise;

我正在使用这个,如果有人知道它有什么问题,请指教;

const integer = parseInt(buffer.toString("hex"), 16)

回答by BlackMamba

you should convert three byte to four byte.

您应该将三字节转换为四字节。

function three(var sample){
    var buffer = new Buffer(sample, 'hex');

    var buf = new Buffer(1);
    buf[0] = 0x0;

    return Buffer.concat([buf, buffer.slice(0, 3)]).readUInt32BE();
}

You can try this function.

你可以试试这个功能。