java如何向ioBuffer分配和检索无符号长值
如何将无符号长值分配给ioBuffer(apachemina)
我的要求是: 我会有一个无符号的长值,即最大值为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!!
这个带符号的eqivalent可以通过一个技巧带回并存储在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。分配(9)。我可以得到如下值:
14769759148312264729
当然我不能分配9个字节。因为无符号长度是8字节。我哪里做错了
有什么想法吗,伙计们
提前谢谢 尼洛帕尔
# 1 楼答案
有符号值和无符号值的二进制表示是相同的,因此您需要的唯一“技巧”是
BigInteger
的符号和幅值构造函数: