UUID.randomUUID()。getLeastSignificantBits()总是返回负值?

时间:2014-11-04 23:50:18

标签: java uuid

我需要生成一个唯一的long值,所以我决定使用UUID:

UUID.randomUUID().getLeastSignificantBits();

我注意到一件奇怪的事情是UUID.randomUUID().getLeastSignificantBits()总是返回负值。我很迷惑。我错过了什么吗?

2 个答案:

答案 0 :(得分:8)

Wikipedia says

  

版本4 UUID使用仅依赖于随机数的方案。该算法设置版本号(4位)以及两个保留位。使用随机或伪随机数据源设置所有其他位(剩余的122位)。

     

版本4 UUID的格式为xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx,其中x是任意十六进制数字,y是8,9,A或B中的一个

因此,最不重要的一半的第一位将始终为1,使其成为负数。

答案 1 :(得分:1)

这可能有助于展示对getLeastSignificantBits()

的期望
/**
 * @see UUID#getLeastSignificantBits()
 */
public void test_getLeastSignificantBits() {
    UUID uuid = new UUID(0, 0);
    assertEquals(0, uuid.getLeastSignificantBits());
    uuid = new UUID(0, Long.MIN_VALUE);
    assertEquals(Long.MIN_VALUE, uuid.getLeastSignificantBits());
    uuid = new UUID(0, Long.MAX_VALUE);
    assertEquals(Long.MAX_VALUE, uuid.getLeastSignificantBits());
}

source