node.jsbufferint128

How to write 128Int or 256Int to Buffer in nodejs


I have a BigInt 170141183460469231731687303715884105728n which is 128 bit integer, then i want to convert that integer to buffer.

But as i know, nodejs Buffer is doesn't support 128 or 256 bit integer, only 64 bit integer they supported.

So the question is, how to convert that integer to buffer? i have search in internet but i didn't find anything.

Sorry if my English is bad, thanks you for your answer.


Solution

  • I found a way to fix this issue, i do looping 16 times (Buffer length of 128Int is 16, 256Int is 32) then shift right with 8 (Buffer length of 64Int) * index of looping on the bigint and do bitwise and (&=) with 255 (range max of buffer). Maybe someone found a better way than this.

    function int_128_to_bytes(int){
      const bytesArray = []; 
      for(let i = 0; i < 16; i++){
         let shift = int >> BigInt(8 * i)
         shift &= BigInt(255)
         bytesArray[i] = Number(String(shift))
      }
      return Buffer.from(bytesArray)
    }
    
    console.log(int_128_to_bytes(BigInt(2 ** 127 -1)).toString("hex") // 00000000000000000000000000000080