简体   繁体   English

如何将 Javascript 数字转换为 Uint8Array?

[英]How to convert a Javascript number to a Uint8Array?

I have a Javascript integer (whose precision can go up to 2^53 - 1 ), and I am trying to send it over the wire using an ArrayBuffer .我有一个 Javascript integer (其精度可以 go 高达2^53 - 1 ),我正在尝试使用ArrayBuffer通过电线发送它。 I suppose I could use BigInt64Array , but the browser support still seems relatively new with that.我想我可以使用BigInt64Array ,但浏览器支持似乎仍然相对较新。

I cannot use Int32Array (which was my original solution), because the precision for that is up to 2^32 - 1 , whereas a Javascript integer can safely go up to 2^53 - 1 .我不能使用Int32Array (这是我的原始解决方案),因为它的精度高达2^32 - 1 ,而 Javascript integer 可以安全地 Z34D1F91FB2E514B816A^BZ8 到2^53 - 1 32FAB1A7538。 This is my problem.这是我的问题。

Is there an easy way to simply turn any Javascript integer into a Uint8Array of length 8?有没有一种简单的方法可以简单地将任何 Javascript integer 变成长度为 8 的Uint8Array

For example, I am looking for a function like this:例如,我正在寻找这样的 function:

function numToUint8Array(num) {
  let arr = new Uint8Array(8);

  // fill arr values with that of num

  return arr;
}

let foo = numToUint8Array(9458239048);
let bar = uint8ArrayToNum(foo); // 9458239048

Does something like this exist in the standard library already?标准库中是否已经存在类似的东西? If not, is there a way to write something like this?如果没有,有没有办法写这样的东西?

@Bergi, is something like this what you had in mind? @Bergi,您的想法是这样的吗?

 function numToUint8Array(num) { let arr = new Uint8Array(8); for (let i = 0; i < 8; i++) { arr[i] = num % 256; num = Math.floor(num / 256); } return arr; } function uint8ArrayToNumV1(arr) { let num = 0; for (let i = 0; i < 8; i++) { num += Math.pow(256, i) * arr[i]; } return num; } function uint8ArrayToNumV2(arr) { let num = 0; for (let i = 7; i >= 0; i--) { num = num * 256 + arr[i]; } return num; } let foo = numToUint8Array(9458239048); let bar = uint8ArrayToNumV1(foo); // 9458239048 let baz = uint8ArrayToNumV2(foo); // 9458239048 console.log(foo, bar, baz);

If you don't want to use Math class, you can use this script:如果你不想使用 Math class,你可以使用这个脚本:

function numToUint8Array(num) {
  const arr = new Uint8Array(8);
  
  for(let i = 0; i < 8; i++)
    arr.set([num/0x100**i], 7-i)

  return arr;
}

function uint8ArrayToNum(arr) {
   let num = 0;
   
   for(let i = 0; i < 8; i++)
      num += (0x100**i) * arr[7-i];
   return num;
}

Test Code:测试代码:

  const arr = numToUint8Array(257);
  console.log(arr);
  const num = uint8ArrayToNum(arr);
  console.log(num);

Result:结果:

Uint8Array(8) [
  0, 0, 0, 0,
  0, 0, 1, 1
]
257

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM