简体   繁体   English

如何在javascript中将双精度(64位)数转换/存储到32位浮点数或UInt16

[英]How to convert/store a double precision (64bit) number to a 32 bit float or a UInt16 in javascript

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. 我发现通过网络发送一个64位(8字节)的号码有时会过度使用。 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. 但我不知道在javascript中以32位或16位数据存储数字的正确方法。

Here's how you can convert a JavaScript number to an array buffer holding a 32 bit float or a 16 bit unsigned integer: 以下是如何将JavaScript编号转换为包含32位浮点数或16位无符号整数的数组缓冲区:

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

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

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