Skip to content

Instantly share code, notes, and snippets.

@berezovskyi
Created September 4, 2014 12:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berezovskyi/2c4d2a07fa2f35e5e04c to your computer and use it in GitHub Desktop.
Save berezovskyi/2c4d2a07fa2f35e5e04c to your computer and use it in GitHub Desktop.
convert a uuid to biginteger
private BigInteger getBigIntegerFromUuid(UUID randomUUID) {
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(randomUUID.getMostSignificantBits());
bb.putLong(randomUUID.getLeastSignificantBits());
return new BigInteger(bb.array());
}
@wluyima
Copy link

wluyima commented Mar 8, 2017

What if I want to get back an unsigned bitInteger value rather than 2's complement value?

@mariuszs
Copy link

mariuszs commented Sep 30, 2017

The same but you can reverse this operation (and result value is much smaller):

private static BigInteger pair(UUID uuid) {
	BigInteger value1 = BigInteger.valueOf(uuid.getMostSignificantBits());
	BigInteger value2 = BigInteger.valueOf(uuid.getLeastSignificantBits());
	if (value1.compareTo(value2) < 0) {
		return value2.multiply(value2).add(value1);
	}
	return value1.multiply(value1).add(value1).add(value2);
}

@drmalex07
Copy link

Another approach using unsigned longs can be found here:
https://gist.github.com/drmalex07/9008c611ffde6cb2ef3a2db8668bc251

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment