Skip to content

Instantly share code, notes, and snippets.

@adamretter
Created May 18, 2015 11:49
Show Gist options
  • Save adamretter/bdbd2aa0fd8b00511db9 to your computer and use it in GitHub Desktop.
Save adamretter/bdbd2aa0fd8b00511db9 to your computer and use it in GitHub Desktop.
UUID to BigInteger rountrip
package javaapplication1;
import java.math.BigInteger;
import java.util.UUID;
public class JavaApplication1 {
public static void main(String[] args) {
final UUID uuid = UUID.randomUUID();
System.out.println("uuid=" + uuid.toString());
final long msb = uuid.getMostSignificantBits();
final long lsb = uuid.getLeastSignificantBits();
System.out.println("msb=" + msb);
System.out.println("lsb=" + lsb);
BigInteger number = BigInteger.valueOf(msb);
number = number.shiftLeft(64);
number.or(BigInteger.valueOf(lsb));
System.out.println("number=" + number);
//now reverse the process to reconstruct our uuid from the big integer
System.out.println();
final long lsb2 = number.and(BigInteger.valueOf(0xFFFFFFFFFFFFFFFFl)).longValue();
final long msb2 = number.shiftRight(64).and(BigInteger.valueOf(0xFFFFFFFFFFFFFFFFl)).longValue();
System.out.println("msb2=" + msb);
System.out.println("lsb2=" + lsb);
final UUID uuid2 = new UUID(msb2, lsb2);
System.out.println("uuid2=" + uuid2.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment