如何将两个16位整数(高位字/低位字)转换为32位浮点数? [英] How To Convert Two 16bit Integer (High Word / Low Word) into 32bit Float?
问题描述
我有两个16位整数原始数据。
I have two 16bit integer raw data.
例如:
High Word = 17142(dec)或0100001011110110(binary)
Low Word = 59759(dec )或1110100101111001(二进制)
For example:
High Word = 17142 (dec) or 0100001011110110 (binary)
Low Word = 59759 (dec) or 1110100101111001 (binary)
如果将两个单词一起视为一个32位浮点数据,它将为123.456
二进制 - > 01000010111101101110100101111001
If you treat two word together as one 32bit float data, it will be "123.456"
Binary --> 01000010111101101110100101111001
如何在Javascript中将整数数组[59759,17142]转换为浮点123.456?
How to convert integer array [59759 , 17142] to float 123.456 in Javascript?
注意:[ X(16位低位字),Y(16位高位字)] ==> Z(32位浮点数)
Note: [ X (16bit low word) , Y (16 bit high word) ] ==> Z (32bit float)
推荐答案
你可以使用类型化数组和 ArrayBuffer
,允许您以不同的方式解释相同的位(但字节顺序是特定于平台的)。也可以使用 DataView缓冲区上的
,可以让你控制字节顺序。
You can do this with typed arrays and ArrayBuffer
, which allow you to interpret the same bits in different ways (but endianness is platform-specific). It's also possible using a DataView
on the buffer, which lets you conrol endianness.
这是类型化的数组方法,它与我的平台的字节顺序一致,看评论:
Here's the typed array approach which works with the endianness of my platform, see comments:
// Create a buffer
var buf = new ArrayBuffer(4);
// Create a 16-bit int view of it
var ints = new Uint16Array(buf);
// Fill in the values
ints[0] = 59759;
ints[1] = 17142;
// Create a 32-bit float view of it
var floats = new Float32Array(buf);
// Read the bits as a float; note that by doing this, we're implicitly
// converting it from a 32-bit float into JavaScript's native 64-bit double
var num = floats[0];
// Done
console.log(num);
这是 DataView
的方法,注意写作以相反顺序的整数:
Here's the DataView
approach, note writing the ints in the opposite order:
// Create a buffer
var buf = new ArrayBuffer(4);
// Create a data view of it
var view = new DataView(buf);
// Write the ints to it
view.setUint16(0, 17142);
view.setUint16(2, 59759);
// Read the bits as a float; note that by doing this, we're implicitly
// converting it from a 32-bit float into JavaScript's native 64-bit double
var num = view.getFloat32(0);
// Done
console.log(num);
这篇关于如何将两个16位整数(高位字/低位字)转换为32位浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!