将UUID转换为BigInteger或从BigInteger转换时出现BufferUnderflowException

时间:2018-02-22 19:17:42

标签: uuid biginteger

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

@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);
}

1 个答案:

答案 0 :(得分:1)

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

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());
}