如何将两个16位整数(高位字/低位字)转换为32位浮点数?

时间:2016-12-05 09:15:43

标签: javascript

我有两个16位整数原始数据。

例如:
高字= 17142(十进制)或0100001011110110(二进制)
低字= 59759(十进制)或1110100101111001(二进制)

如果将两个单词一起视为一个32位浮点数据,则为“123.456”
二进制 - > 01000010111101101110100101111001

如何在Javascript中将整数数组[59759,17142]转换为浮点123.456?

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

1 个答案:

答案 0 :(得分:5)

您可以使用typed arraysArrayBuffer执行此操作,这允许您以不同方式解释相同的位(但字节顺序是特定于平台的)。它也可以在缓冲区上使用DataView,这样可以控制字节顺序。

这是使用我的平台的字节顺序的类型化数组方法,请参阅注释:



created_at




这里是<div class="text-center"> <!-- PRIMO BOTTONE --> <s:form action="esportaCommesseByRichiesta" cssClass="form-same-row"> <button type="submit" class="btn btn-success btn-xs" data-toggle="tooltip" title="Esporta Richiesta"> <span class="glyphicon glyphicon-floppy-save" aria-hidden="true"></span> </button> </s:form> <!-- PRIMO BOTTONE --> <!-- SECONDO BOTTONE --> <s:form action="editCommesseGl" cssClass="form-same-row"> <button type="submit" class="btn btn-info btn-xs" title="Modifica Richiesta"> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> </button> </s:form> <!-- SECONDO BOTTONE --> <!-- TERZO BOTTONE --> <s:form action="#" cssClass="form-same-row"> <button type="submit" class="btn btn-danger btn-xs" data-toggle="tooltip" title="Cancella Richiesta"> <span class="glyphicon glyphicon-remove" aria-hidden="true"></span> </button> </s:form> <!-- TERZO BOTTONE --> </div>方法,请注意以相反的顺序写入整数:

&#13;
&#13;
// 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);
&#13;
&#13;
&#13;