我使用GO语言函数(math.Float32bits)序列化了32位浮点数,它返回对应于IEEE 754二进制表示的浮点数。然后将此数字序列化为32位整数,并作为字节数组读入java脚本。
例如,这是实际数字:
float: 2.8088086
as byte array: 40 33 c3 85
as hex: 0x4033c385
有demo converter显示相同的数字。
我需要从JavaScript中的字节数组中获取相同的浮点数,我不知道该怎么做。
答案 0 :(得分:5)
根据您描述的数据:
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);
// 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));
答案 1 :(得分:3)
有点不同的解决方案,如果你不能使用DataView:
formLogin.Close();
答案 2 :(得分:0)
我的回答就像@Jeremys 的回答,只是有一些小改动。请现在使用 const
/let
和 Float32Array
/Float64Array
而不是 DataView
。我是这样解决的:
// 0x40a00000 is "5" in float/IEEE-754 32bit.
// You can check this here: https://www.h-schmidt.net/FloatConverter/IEEE754.html
// MSB (Most significant byte) is at highest index
const bytes = [0x00, 0x00, 0xa0, 0x40];
// The buffer is like a raw view into memory.
const buffer = new ArrayBuffer(bytes.length);
// The Uint8Array uses the buffer as its memory.
// This way we can store data byte by byte
const byteArray = new Uint8Array(buffer);
for (let i = 0; i < bytes.length; i++) {
byteArray[i] = bytes[i];
}
// float array uses the same buffer as memory location
const floatArray = new Float32Array(buffer);
// floatValue is a "number", because a number in javascript is a
// double (IEEE-754 @ 64bit) => it can hold f32 values
const floatValue = floatArray[0];
// prints out "5"
console.log(`${JSON.stringify(bytes)} as f32 is ${floatValue}`);
// double / f64
// const doubleArray = new Float64Array(buffer);
// const doubleValue = doubleArray[0];