问题描述
假设我有一个十六进制数据流,我想把它分成3个字节的块,我需要读取整数。
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.
例如:给定十六进制字符串 01be638119704d4b9a
我需要读取前三个字节 01be63
并将其读作整数 114275
。这就是我得到的:
For example: given a hex string 01be638119704d4b9a
I need to read the first three bytes 01be63
and read it as integer 114275
. This is what I got:
var sample = '01be638119704d4b9a';
var buffer = new Buffer(sample, 'hex');
var bufferChunk = buffer.slice(0, 3);
var decimal = bufferChunk.readUInt32BE(0);
readUInt32BE
适用于4字节数据,但在这里我显然得到:
The readUInt32BE
works perfectly for 4-bytes data, but here I obviously get:
RangeError: index out of range
at checkOffset (buffer.js:494:11)
at Buffer.readUInt32BE (buffer.js:568:5)
如何我是否正确读取3字节作为整数?
How do I read 3-bytes as integer correctly?
推荐答案
如果您使用的是node.js v0.12 +或io.js ,有允许可变数量的字节:
If you are using node.js v0.12+ or io.js, there is buffer.readUIntBE()
which allows a variable number of bytes:
var decimal = buffer.readUIntBE(0, 3);
(请注意,Big Endian的 readUIntBE
对于Little Endian, readUIntLE
。
(Note that it's readUIntBE
for Big Endian and readUIntLE
for Little 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];
这篇关于JavaScript:读取3个字节Buffer作为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!