0

I am trying to code a UUID using .hashCode

At the moment my code generates a uniqueID value but wondering how to stop negative values being generated?

int uniqueID = UUID.randomUUID().hashCode();
System.out.println (uniqueID);

Thanks

APPAPA
  • 25
  • 1
  • 6

1 Answers1

3

Try this:

int uniqueID = UUID.randomUUID().hashCode() & Integer.MAX_VALUE;
System.out.println (uniqueID);

Note:

  • Integer.MAX_VALUE represents the maximum positive value for a 32-bit signed binary integer.
  • The & symbol is a bitwise AND operator.
  • It works because when we bitwise & with 1 it returns the same digit and when we bitwise & with 0 it results in 0.
  • Now Integer.MAX_VALUE results 2147483647 in decimal value and 01111111111111111111111111111111 in the binary value (32 bit where leftmost bit represents sign i.e. 0 for positive and 1 for negative).
  • So when we bitwise & a number with this above binary number then we get the same number except that the leftmost bit is now turned into a zero which means we have changed the sign of that number and not it's value.
Nitin Bisht
  • 5,053
  • 4
  • 14
  • 26