我有一个 BigInt
170141183460469231731687303715884105728n
,它是 128 位整数,然后我想将该整数转换为缓冲区。
但据我所知,nodejs Buffer 不支持 128 或 256 位整数,仅支持 64 位整数。
那么问题是,如何将该整数转换为缓冲区?我在互联网上搜索过,但没有找到任何东西。
抱歉,如果我的英语不好,谢谢您的回答。
我找到了解决这个问题的方法,我循环
16
次(128Int的缓冲区长度是16
,256Int是32
)然后向右移动8
(64Int的缓冲区长度)在 bigint 上 *
index of looping
并执行 bitwise and
(&=
) 与 255
(缓冲区最大范围)。也许有人找到了比这更好的方法。
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
如果您可以使用库,bigint-buffer具有用于在缓冲区中读取和写入
BigInt
值的实用程序。
const { toBigIntLE, toBufferLE } = require("@trufflesuite/bigint-buffer");
const buffer = toBufferLE(170141183460469231731687303715884105728n, 16);
// <Buffer 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 80>
const bigInt = toBigIntLE(buffer);
// 170141183460469231731687303715884105728n
如果您不想使用库,您可以通过十六进制字符串进行转换。请注意,此代码以大端字节顺序存储数字,并且不支持负数。
function bigIntToBuffer(bigInt) {
const hexString = bigInt.toString(16);
const padding = hexString.length % 2 == 1 ? "0" : "";
return Buffer.from(padding + hexString, "hex");
}
const buffer = bigIntToBuffer(170141183460469231731687303715884105728n);
// <Buffer 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00>
function bufferToBigInt(buffer) {
return BigInt("0x" + buffer.toString("hex"));
}
const bigInt = bufferToBigInt(buffer);
// 170141183460469231731687303715884105728n