如何将javascript BigInt转换为考虑负值的Uint8Array

如何将javascript BigInt转换为考虑负值的Uint8Array,javascript,bigint,uint8array,Javascript,Bigint,Uint8array,我有一个java后端,它通过javascript前端使用字节读取/写入任意精度的数字 在Java方面,我只做: new BigInteger(“123”).toByteArray() 医生说: Returns a byte array containing the two's-complement representation of this BigInteger. 在javascript方面,我需要将字节读入javascript的BigInt,反之亦然 我让javascript将字节读入

我有一个java后端,它通过javascript前端使用字节读取/写入任意精度的数字

在Java方面,我只做:

new BigInteger(“123”).toByteArray()
医生说:

Returns a byte array containing the two's-complement 
representation of this BigInteger.
在javascript方面,我需要将字节读入javascript的BigInt,反之亦然

我让javascript将字节读入BigInt,如下所示:

const hex = Buffer.from(bytes).toString('hex')
let big = BigInt('0x' + hex)
if (a[0] & 0x80) {
  const negative = BigInt('0x1' + '0'.repeat(hex.length))
  big -= negative
}

但将BigInt转换为字节似乎非常棘手。我环顾四周,发现其他的解决方案都只涉及正数,而不涉及负数

在深入研究并理解了补码表示法之后,我回答了自己的问题:

const big0=BigInt(0)
常量big1=BigInt(1)
常量big8=BigInt(8)
函数bigtoint8array(大:bigint){
如果(大<大0){
//计算出大整数的长度(以位为单位),然后加1
常量位:bigint=(bigint(big.toString(2.length)/big8+big1)*big8
//创建一个长度为100000的BigInt,长度为big+1

const prefix1:bigint=big1这段代码不允许调用方指定他们想要的bigint值是以小端字节顺序还是以大端字节顺序表示。另外,你的问题是什么?@dai很抱歉没有正确地编写问题。那天晚上很晚或很早:D我只是没有正确地编写它。但是我通过了很长一段时间以来,我一直希望其他人会觉得它有用