如何将无符号的 Long 值分配给 ioBuffer(apache mina)
我的要求是: 我会有一个无符号的 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()));
现在,当我分配 8bytes 时,我得到一个异常:
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 个字节。我哪里错了!!
大家有什么想法吗!!
提前致谢 尼洛特帕尔
最佳答案
有符号和无符号值的二进制表示形式是相同的,因此您需要的唯一“技巧”是 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
关于java - 如何向 ioBuffer 分配和检索无符号 Long 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50899018/