Skip to content

Instantly share code, notes, and snippets.

@mpaltun
Forked from adamretter/JavaApplication1.java
Created February 14, 2023 14:52
Show Gist options
  • Save mpaltun/1b9a45340a38ed058f1d9d11d97b4f80 to your computer and use it in GitHub Desktop.
Save mpaltun/1b9a45340a38ed058f1d9d11d97b4f80 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