简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM