如何为ioBuffer

时间:2018-06-17 17:38:49

标签: java nio bytebuffer apache-mina

如何将无符号Long值分配给ioBuffer(apache mina)

我的要求是: 我会有一个无符号长值,即一个值高达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!!

这个签名的eqiivalent可以带回来并存放在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个字节。因为无符号长是8个字节。我哪里错了!!

任何想法的人!!

提前致谢 Nilotpal

1 个答案:

答案 0 :(得分:2)

有符号和无符号值的二进制表示是相同的,因此唯一的"技巧"你需要的是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