我正在寻找将两个32位数字组合成JavaScript中的单个64位数字,然后相反的方法。
基本上我想将以下C代码转换为JavaScript:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
int main()
{
// Combines two numbers into one
uint64_t left = 12;
uint64_t right = 2000;
uint64_t smushed = (left << 32) | (right & 0xFFFFFFFF);
printf("Smushed: %lu\n", smushed); // Outputs: Smushed: 51539609552
printf("Left: %lu\n", (smushed >> 32)); // Outputs: Left: 12
printf("Right: %lu\n", (smushed & 0xFFFFFFFF)); // Outputs: Right: 2000
return 0;
}
我能够通过BigInt做到这一点:
const left = BigInt(12);
const right = BigInt(2000);
const smushed = (left << BigInt(32)) | (right & BigInt(0xFFFFFFFF));
console.log("Smushed: %d", smushed);
console.log("Left: %d", (smushed >> BigInt(32)));
console.log("Right: %d", (smushed & BigInt(0xFFFFFFFF)));
但是BigInt支持对于Chrome和Firefox都是非常新的。
没有BigInt的JavaScript是否有办法做到这一点?
看MDN documentation,可以表示的最大整数为2^53 - 1
的长度。
所以答案是否定的。您可以在javascript中原生使用64位整数