Last active
October 18, 2024 06:10
-
-
Save drmalex07/9008c611ffde6cb2ef3a2db8668bc251 to your computer and use it in GitHub Desktop.
Convert a UUID to an unsigned BigInteger #java #UUID #BigInteger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static final BigInteger B = BigInteger.ONE.shiftLeft(64); // 2^64 | |
public static final BigInteger L = BigInteger.valueOf(Long.MAX_VALUE); | |
public static BigInteger convertToBigInteger(UUID id) | |
{ | |
BigInteger lo = BigInteger.valueOf(id.getLeastSignificantBits()); | |
BigInteger hi = BigInteger.valueOf(id.getMostSignificantBits()); | |
// If any of lo/hi parts is negative interpret as unsigned | |
if (hi.signum() < 0) | |
hi = hi.add(B); | |
if (lo.signum() < 0) | |
lo = lo.add(B); | |
return lo.add(hi.multiply(B)); | |
} | |
public static UUID convertFromBigInteger(BigInteger x) | |
{ | |
BigInteger[] parts = x.divideAndRemainder(B); | |
BigInteger hi = parts[0]; | |
BigInteger lo = parts[1]; | |
if (L.compareTo(lo) < 0) | |
lo = lo.subtract(B); | |
if (L.compareTo(hi) < 0) | |
hi = hi.subtract(B); | |
return new UUID(hi.longValueExact(), lo.longValueExact()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And one string based option for converting back: