0

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.

butthx
  • 11
  • 1
  • 4
  • You could convert the BigInt to a string of digits and store the string. Then, you don't have to use a Buffer at all. And, reading the data from the string will be simple also. – jfriend00 Jul 02 '22 at 06:30

1 Answers1

1

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
butthx
  • 11
  • 1
  • 4