在JavaScript中将IEEE 754从位流转换为浮点数 [英] Converting IEEE 754 from bit stream into float in JavaScript
问题描述
我使用GO语言功能序列化了32位浮点数( math.Float32bits )返回对应于IEEE 754二进制表示的浮点数。然后将此数字序列化为32位整数,并作为字节数组读入java脚本。
例如,这是实际数字:
float:2.8088086
as byte array:40 33 c3 85
as hex:0x4033c385
有一个 demo converter 显示相同的数字。
我需要从JavaScript中的字节数组中获取相同的浮点数,我不知道该怎么做鉴于您所描述的数据:
var buffer = new ArrayBuffer(4);
var bytes = new Uint8Array(buffer);
bytes [0] = 0x40;
bytes [1] = 0x33;
bytes [2] = 0xc3;
bytes [3] = 0x85;
我们可以使用 DataView
:
var view = new DataView(buffer);
//如果你只有一个Uint8Array,你会使用bytes.buffer而不是buffer。
console.log(view.getFloat32(0,false));
2.8088085651397705
var buffer = new ArrayBuffer(4 ); var bytes = new Uint8Array(buffer); bytes [0] = 0x40; bytes [1] = 0x33; bytes [2] = 0xc3; bytes [3] = 0x85; var view = new DataView(buffer); console.log(view.getFloat32(0,false));
I have serialized 32-bit floating number using GO language function (math.Float32bits) which returns the floating point number corresponding to the IEEE 754 binary representation. This number is then serialized as 32-bit integer and is read into java script as byte array.
For example, here is actual number:
float: 2.8088086
as byte array: 40 33 c3 85
as hex: 0x4033c385
There is a demo converter that displays the same numbers.
I need to get that same floating number back from byte array in JavaScript and I have no idea how to do that.
Given the data you've described:
var buffer = new ArrayBuffer(4);
var bytes = new Uint8Array(buffer);
bytes[0] = 0x40;
bytes[1] = 0x33;
bytes[2] = 0xc3;
bytes[3] = 0x85;
We can retrieve the value as a floating-point number using a DataView
:
var view = new DataView(buffer);
// If you only had a Uint8Array, you would use bytes.buffer instead of buffer.
console.log(view.getFloat32(0, false));
2.8088085651397705
var buffer = new ArrayBuffer(4);
var bytes = new Uint8Array(buffer);
bytes[0] = 0x40;
bytes[1] = 0x33;
bytes[2] = 0xc3;
bytes[3] = 0x85;
var view = new DataView(buffer);
console.log(view.getFloat32(0, false));
这篇关于在JavaScript中将IEEE 754从位流转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!