UUID.randomUUID (). Does GetLeastSignificantBits () always return negative values?

I need to create a unique long value, so I decided to use the UUID:

UUID.randomUUID().getLeastSignificantBits(); 

One strange thing I noticed was that UUID.randomUUID().getLeastSignificantBits() always returned negative values. I'm confused. Did I miss something?

+5
source share
2 answers

Wikipedia says :

Version 4 UUIDs use a random-number-based scheme. This algorithm sets the version number (4 bits), as well as two reserved bits. All other bits (the remaining 122 bits) are set using a random or pseudo-random data source.

Version 4 UUIDs are of the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx, where x is any hexadecimal digit and y is one of 8, 9, A or B

So, the first bit of the least significant half will always be 1, which makes it a negative number.

+6
source

It can also be useful to demonstrate what to expect from 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()); } 

a source

+1
source

Source: https://habr.com/ru/post/1206211/


All Articles