nodejs write 64bit unsigned integer to buffer

后端 未结 6 782
遥遥无期
遥遥无期 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条回答
  •  Happy的楠姐
    2021-02-14 03:45

    Bitwise operations in JavaScript/EcmaScript will force the number (or any value really) into a 32-bit integer.

    You really need to use bignum for larger values if you need certain precision, or dealing with buffers with larger than 32-bit values.

    var bignum = require('bignum');
    
    //max safe integer to big number
    var num = bignum(Number.MAX_SAFE_INTEGER.toString());
    var buf = num.toBuffer({endian:'big',size:8 /*8-byte / 64-bit*/});
    
    console.log(buf); // 

    The example above uses Number.MAX_SAFE_INTEGER which is Math.pow(2,53)-1. If you need to use larger numbers, they should be accessed as bignum strings... if you can stay within the range of Integers in JS, you can keep them and convert as above.

提交回复
热议问题