如何在JavaScript中将双精度(64位)数字转换/存储为32位浮点数或UInt16 [英] How to convert/store a double precision (64bit) number to a 32 bit float or a UInt16 in javascript

查看:1551
本文介绍了如何在JavaScript中将双精度(64位)数字转换/存储为32位浮点数或UInt16的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我可以在一定程度上消除数字/精度的损失。我发现通过网络发送一个64位(8字节)的号码有时是过度的。我希望数据使用更少的带宽,但保持一定的准确性。但我不知道正确的方式来存储一个数字在JavaScript中的32位或16位数据。

你可以将一个JavaScript数字转换成一个32位浮点数或一个16位无符号整数的数组缓冲区:
$ b

  let float64 = 3.141592653589793238462643383279502884197; let float32View = new DataView(new ArrayBuffer(4)); float32View.setFloat32(0,float64); let uint16View = new DataView(new ArrayBuffer(2)); uint16View.setUint16 (0,float64); console.log(float64); console.log(float32View.getFloat32(0)); console.log(uint16View.getUint16(0));  


Assume I can bare the loss of digits/precision to some degree. I find that to send a 64bit (8 bytes) number over the network sometimes is overkilled. I want the data to use less bandwidth but maintain certain accuracy. But I don't know the correct way to store a number in 32 bit or 16 bit data in javascript.

解决方案

Here's how you can convert a JavaScript number to an array buffer holding a 32 bit float or a 16 bit unsigned integer:

let float64 = 3.141592653589793238462643383279502884197;

let float32View = new DataView(new ArrayBuffer(4));
float32View.setFloat32(0, float64);

let uint16View = new DataView(new ArrayBuffer(2));
uint16View.setUint16(0, float64);

console.log(float64);
console.log(float32View.getFloat32(0));
console.log(uint16View.getUint16(0));

这篇关于如何在JavaScript中将双精度(64位)数字转换/存储为32位浮点数或UInt16的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆