2016-12-05 665 views
1

我有兩個16位整數原始數據。如何將兩個16位整數(高位字/低位字)轉換爲32位浮點數?

例如:
高位字= 17142(分解)或0100001011110110(二進制)
低位字= 59759(分解)或1110100101111001(二進制)

如果對待兩條字在一起作爲一個32位的浮點數據,這將是 「123.456」
二進制 - > 01000010111101101110100101111001

如何整數數組[59759,17142]浮動123.456轉換的Javascript?

注:X(16位低位字),Y(16位高字)] ==> Z(32位浮點)

回答

3

你可以用typed arraysArrayBuffer,它允許你去解釋同樣做到這一點位以不同的方式(但是字節序是平臺特定的)。也可以在緩衝區上使用DataView,這可以讓您控制字節順序。

這裏的類型數組的方式與我的平臺的字節序的作品,看評論:

// 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方法,注意以相反的順序寫整數:

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

+1

@Crowder It works!非常感謝你的回答 –

相關問題