Skip to content

Instantly share code, notes, and snippets.

@lotuc
Last active August 24, 2023 14:07
Show Gist options
  • Save lotuc/8ea8d51856af05f3087b703d3e927a47 to your computer and use it in GitHub Desktop.
Save lotuc/8ea8d51856af05f3087b703d3e927a47 to your computer and use it in GitHub Desktop.
JavaScript implementation of java.util.UUID's stringify
// 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