nodejs write 64bit unsigned integer to buffer

后端 未结 6 748
遥遥无期
遥遥无期 2021-02-14 03:08

I want to store a 64bit (8 byte) big integer to a nodejs buffer object in big endian format.

The problem about this task is that nodejs buffer only supports writing 32bi

6条回答
  •  闹比i
    闹比i (楼主)
    2021-02-14 03:49

    I think what you are looking for is:

    var bufInt = (buf.readUInt32BE(0) << 8) + buf.readUInt32BE(4);
    

    Shift the first number by 8 bits and add (instead of multiplying), wich returns 65535


    EDIT

    Another way to write would be:

    var buf = new Buffer(8);
    buf.fill(0);
    
    var i = 0xCDEF; // 52719 in decimal
    
    buf.writeUInt32BE(i >> 8, 0); //write the high order bits (shifted over)
    buf.writeUInt32BE(i & 0x00ff, 4); //write the low order bits
    
    console.log(buf); //displays: 
    
    var bufInt = (buf.readUInt32BE(0) << 8) + buf.readUInt32BE(4);
    console.log(bufInt); //displays: 52719
    

提交回复
热议问题