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
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
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.&
symbol is a bitwise AND
operator.&
with 1
it returns the same digit and when we bitwise &
with 0
it results in 0
.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).&
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.