如何为 ioBuffer 分配和检索无符号 Long 值

How to assign and retrieve a unsigned Long value to ioBuffer

如何为 ioBuffer( apache mina) 分配一个无符号的 Long 值

我的要求是: 我会有一个无符号的 Long 值,即高达 2^64-1 = 18446744073709551615 的值, 需要将其设置为 ioBuffer 然后取回。

我可以在中线或任何适合的策略中使用 BigInteger :

long var1 = -3676984925397286887L; // This is signed number whose unsigned equivalent is "14769759148312264729". Actually this is the signed number is what my expectation is in the final output from the ioBuffer. Since Java do not have signed long equivalent, my number is overflowing and turning to a negative number!!

这个带符号的等价物可以用一个技巧取回并存储在 BigInteger 中!!

 long quot = (var1 >>> 1) / 5;
 Long rem = var1 - quot * 10;
 BigInteger bi = BigInteger.valueOf(quot).multiply(new BigInteger("10")).add(new BigInteger(rem.toString()));//.multiply(new BigInteger("10").add(new BigInteger(rem+"")));//new BigInteger(quot).multiply(10).add(rem);
    System.out.println(bi);

到目前为止一切都很好。现在我希望它存储在 ioBuffer 中。

IoBuffer ioBuffer1 = IoBuffer.allocate(8);
    ioBuffer1.put(bi.toByteArray());
    System.out.println(new BigInteger(ioBuffer1.array()));

现在,当我分配 8 个字节时,我得到一个异常:

Exception in thread "main" java.nio.BufferOverflowException
at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:189)
at org.apache.mina.core.buffer.AbstractIoBuffer.put(AbstractIoBuffer.java:654)
at org.apache.mina.core.buffer.AbstractIoBuffer.put(AbstractIoBuffer.java:1355)

但如果我将其更改为 ioBuffer.allocate(9)。我能够获得以下值:

14769759148312264729

当然我不能分配 9 个字节。因为 unsigned long 是 8 个字节。我哪里错了!!

任何想法伙计们!!

提前致谢 尼洛帕尔

有符号和无符号值的二进制表示相同,因此您唯一需要的 "trick" 是 BigInteger 的符号和大小构造函数:

long var1 = -3676984925397286887L;

IoBuffer ioBuffer1 = IoBuffer.allocate(8);
ioBuffer1.putLong(var1);

BigInteger bi = new BigInteger(1, ioBuffer1.array());

System.out.println(bi);             // 14769759148312264729
System.out.println(bi.longValue()); // -3676984925397286887