JavaScript从两个长数字构造UUID



我有两个长数字,我用BigInt表示JavaScript中的数字(因为JavaScipt中的整数长度是53位,而不是64位(。我发现自己需要在这两个长数字中创建一个JavaScript中的UUID/GGUID。

在SO中,我能够多次找到相同的问题,但总是针对不同的编程语言,但不针对JavaScript,例如:

基本上,我正在寻找类似Java中的东西,例如这里的例子:

public UUID(long mostSigBits, long leastSigBits) {
this.mostSigBits = mostSigBits;
this.leastSigBits = leastSigBits;
}

我们可以像一样使用它

UUID  tempUUID1 = new UUID(55, 100);

结果在:

00000000-0000-0037-0000-000000000064

到目前为止,我想采取的方法是像一样将十进制转换为十六进制

BigInt("55").toString('16')     // results to 37
BigInt("100").toString('16')    // results to 64

然后填充缺失的零。如何实现这样的功能,我正在寻找一个例子。

最好使用WebCryptoAPI(不幸的是node.js不是我在这里寻找的(,它可以创建和读取/拆分这样的UUID/GGUID到2个单独的BigInt,即";mostSigBits";以及";最小SigBits";价值观

如果有人能提供这样一个函数/方法的例子,我将不胜感激。提前谢谢。

不需要库,格式化这些数字非常简单substring'ing:

function formatAsUUID(mostSigBits, leastSigBits) {
let most = mostSigBits.toString("16").padStart(16, "0");
let least = leastSigBits.toString("16").padStart(16, "0");
return `${most.substring(0, 8)}-${most.substring(8, 12)}-${most.substring(12)}-${least.substring(0, 4)}-${least.substring(4)}`;
}

function formatAsUUID(mostSigBits, leastSigBits) {
let most = mostSigBits.toString("16").padStart(16, "0");
let least = leastSigBits.toString("16").padStart(16, "0");
return `${most.substring(0, 8)}-${most.substring(8, 12)}-${most.substring(12)}-${least.substring(0, 4)}-${least.substring(4)}`;
}

const expect = "00000000-0000-0037-0000-000000000064";
const result = formatAsUUID(BigInt("55"), BigInt("100"));
console.log(result, expect === result ? "OK" : "<== Error");

最新更新