nodejs write 64bit unsigned integer to buffer

后端 未结 6 747
遥遥无期
遥遥无期 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条回答
  •  太阳男子
    2021-02-14 03:44

    Reading and writings UINT numbers up to Number.MAX_SAFE_INTEGER.

    This works in node.js only, is not portable on browser side.

    function uintToBase62(n) {
      if (n < 0) throw 'unsupported negative integer';
    
      let uintBuffer;
      if (n < 0x7FFFFFFF) {
        uintBuffer = new Buffer(4);
        uintBuffer.writeUInt32BE(n, 0);
      } else {
        // `~~` double bitwise operator
        // The most practical way of utilizing the power of this operator is to use it as a replacement
        // for Math.floor() function as double bitwise NOT performs the same operation a lot quicker.
        // You can use it, to convert any floating point number to a integer without performance overkill
        // that comes with Math.floor(). Additionally, when you care about minification of your code,
        // you end up using 2 characters (2 tildes) instead of 12.
        // http://rocha.la/JavaScript-bitwise-operators-in-practice
        const big = ~~(n / 0x0100000000);
        const low = (n % 0x0100000000);
        uintBuffer = new Buffer(8);
        uintBuffer.writeUInt32BE(big, 0);
        uintBuffer.writeUInt32BE(low, 4);
      }
    
      return uintBuffer.toString('hex');
    }
    

    to convert it

    function uintFromBase62(uintBuffer) {
      const n = parseInt(uintBuffer.toString('hex'), 16);
      return n;
    }
    

提交回复
热议问题