nodejs write 64bit unsigned integer to buffer

后端 未结 6 749
遥遥无期
遥遥无期 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:42

    Reading / Writing 64bit values:

    const int64 = Date.now()   // 1456909977176 (00 00 01 53 36 9a 06 58)
    const b = new Buffer(8)
    const MAX_UINT32 = 0xFFFFFFFF
    
    // write
    const big = ~~(int64 / MAX_UINT32)
    const low = (int64 % MAX_UINT32) - big
    
    b.writeUInt32BE(big, 0)  // 00 00 01 53 00 00 00 00
    b.writeUInt32BE(low, 4)  // 00 00 01 53 36 9a 06 58
    
    // read
    var time = parseInt(b.toString('hex'), 16)
    time == int64 // true
    

    I use this code without any special modules.

    UPDATE

    Works only for numbers <= Number.MAX_SAFE_INTEGER

提交回复
热议问题