[removed] reading 3 bytes Buffer as an integer

前端 未结 3 1151
小蘑菇
小蘑菇 2021-02-07 02:04

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.

For example: given a hex string 01be638119704d4

相关标签:
3条回答
  • 2021-02-07 02:18

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

    const integer = parseInt(buffer.toString("hex"), 16)
    
    0 讨论(0)
  • 2021-02-07 02:28

    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.

    0 讨论(0)
  • 2021-02-07 02:33

    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);
    

    (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];
    
    0 讨论(0)
提交回复
热议问题