JavaScript从两个长数字构造UUID

问题描述

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

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

基本上,我正在寻找类似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 / GUID读取/拆分为2个独立的BigInt,即“ mostSigBits”和“ leastSigBits” “值。

如果有人提供此类功能/方法的示例,我将不胜感激。谢谢你。

解决方法

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

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,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");

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...