Last active
August 24, 2023 14:07
-
-
Save lotuc/8ea8d51856af05f3087b703d3e927a47 to your computer and use it in GitHub Desktop.
JavaScript implementation of java.util.UUID's stringify
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
// https://stackoverflow.com/questions/75387792/javascript-equivalent-of-javas-uuid-class/76967385#76967385 | |
// assume x under range of signed long value | |
function unsignedBitShiftRight(x, n) { | |
if (n === 0) { return x; } | |
else if (x >= 0) { return x >> n; } | |
// convert to two's complement and then do the shifting | |
else { return (((1n << 64n) - 1n) ^ (- (x + 1n))) >> n; } | |
} | |
// lsb & msb are both BigInt | |
// lsb & msb taken from Java's getLeastSignificantBits & getMostSignificantBits | |
function toUuidString(lsb, msb) { | |
return `${ | |
digits(unsignedBitShiftRight(msb, 32n), 8n)}-${ | |
digits(unsignedBitShiftRight(msb, 16n), 4n)}-${ | |
digits(msb, 4n)}-${ | |
digits(unsignedBitShiftRight(lsb, 48n), 4n)}-${ | |
digits(lsb, 12n)}` | |
} | |
function digits(value, ds) { | |
const hi = 1n << (ds * 4n) | |
return (hi | (value & (hi - 1n))).toString(16).slice(1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment