首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BufferUnderflowException同时将UUID转换为/从BigInteger

BufferUnderflowException同时将UUID转换为/从BigInteger
EN

Stack Overflow用户
提问于 2018-02-22 19:17:42
回答 1查看 144关注 0票数 1
代码语言:javascript
复制
public static BigInteger bigInteger(UUID uuid) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return new BigInteger(bb.array());
}

public static UUID uuid(BigInteger value)  {
    byte[] bytes = value.toByteArray();
    ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
    Long high = byteBuffer.getLong();
    Long low = byteBuffer.getLong();
    return new UUID(high, low);
}

为什么下面的测试在java.nio.BufferUnderflowException中失败

代码语言:javascript
复制
@Test
public void testUuidBigInteger_underflow() {
    UUID uuidValue = UUID.fromString("ffe11491-04ab-4602-bd85-08716fb4d384");
    BigInteger bigIntegerValue = bigInteger(uuidValue);
    UUID uuidValue2 = uuid(bigIntegerValue);
    assertEquals(uuidValue, uuidValue2);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-18 20:46:49

在从ByteBuffer写入和读取之间,需要调用.flip()方法--将缓冲区的限制设置为当前位置,位置设置为0,即如下所示:

代码语言:javascript
复制
public static BigInteger bigInteger(UUID uuid) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    bb.flip();
    return new BigInteger(bb.array());
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48935537

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档