Created
February 11, 2020 04:44
-
-
Save imanabu/ea2c2bc206caa9d93c08544cf51c7c77 to your computer and use it in GitHub Desktop.
Encode and Decode a 128-bit UUID to DICOM UID Segment
This file contains 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
private static String dotEncode(long n) { | |
String s = String.format("%d", n); | |
if (s.startsWith("-")) { | |
return ".2" + s.substring(1); | |
} | |
return ".1" + s; | |
} | |
private static long dotDecode(String s) { | |
if (s.startsWith("1")) { | |
return Long.parseLong(s.substring(1)); | |
} | |
if (s.startsWith("2")) { | |
return Long.parseLong("-" + s.substring(1)); | |
} | |
return 0L; | |
} | |
/** | |
* Convert a UUID to two long number segments in a way it will not violate their rule. | |
* It decimal encodes high and low parts, and prefixes each value with 1 if it's positive | |
* or 2 if it is negative. UUID rule disallows a zero after a dot. | |
* It generates 42 characters or so. Limit your prefix to about 20 characters. | |
* | |
* @param uuidOrNull a 128-bit UUID or null to self-generate one. | |
* leaving the . at front. | |
* @return The string that looks like this .17683760201842708094.28650710562283253775 appendable this to your prefix. | |
*/ | |
public static String uuidToUid(UUID uuidOrNull) { | |
final UUID uuid = uuidOrNull == null ? UUID.randomUUID() : uuidOrNull; | |
long h = uuid.getMostSignificantBits(); | |
long lo = uuid.getLeastSignificantBits(); | |
return dotEncode(h) + dotEncode(lo); | |
} | |
/** | |
* Encoded Uid fragment to UUID | |
* Given the UUID fragment converted by uuidToUid plus your prefix, please give the fragment part | |
* including the first dot. | |
* String MUST start with a . and only have two segments like this; | |
* .17683760201842708094.28650710562283253775 | |
* @param s String containing ONLY the encoded UID fragment like .17683760201842708094.28650710562283253775 | |
* @return the decoded 128-bit UUID | |
*/ | |
public static UUID uidToUuid(String s) { | |
String[] t = s.split("\\."); | |
long high = dotDecode(t[1]); | |
long low = dotDecode(t[2]); | |
return new UUID(high, low); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment