简体   繁体   English

JavaScript十六进制字符串到IEEE-754浮点数

[英]JavaScript Hexadecimal string to IEEE-754 Floating Point

I've looked around Stackoverflow for a few days trying to solve this problem and played in JsFiddle for a while but no luck so far. 为了解决这个问题,我在Stackoverflow周围待了几天,并在JsFiddle中玩了一段时间,但到目前为止还没有运气。

Here's my problem: i receive a base64 encoded string which is packed with several values. 这是我的问题:我收到一个base64编码的字符串,其中包含多个值。 Both Unsigned Integers and floating point numbers. 无符号整数和浮点数。 The decoding of the base64 to a hex string goes fine. 可以将base64解码为十六进制字符串。 So do the unsigned integers. 无符号整数也是如此。 The problem lies in decoding the floats. 问题在于解码浮点数。

b76a40e9000000350a3d422d00000059e37c409a0000002f90003b6e00000000

This is my data, as an example well use the first 32 bits, is a IEE-754 float with byte order 1-0-3-2 . 这是我的数据,例如很好地使用前32位,是IEE-754浮点数,字节顺序为1-0-3-2 So that's 0xb76a40e9 which i know is 7.30363941192626953125 and when we swap it to be 3-2-0-1 it becomes 0x40e9b76a . 所以这就是0xb76a40e9 ,我知道是7.30363941192626953125 ,当我们将其交换为3-2-0-1它变为0x40e9b76a When i put this hex string into https://www.h-schmidt.net/FloatConverter/IEEE754.html that is confirmed. 当我将此十六进制字符串放入已确认的https://www.h-schmidt.net/FloatConverter/IEEE754.html中时。

My question is, and iv'e searched for this very long, if there is an implementation in javascript that converts hexadecimal IEEE-754 float strings into a javascript float. 我的问题是,如果在javascript中有一种将十六进制IEEE-754浮点字符串转换为javascript浮点的实现,我会搜索很长时间。 JS' own parseInt will accept hex, but parseFloat doesn't for some reason? JS自己的parseInt将接受十六进制,但是由于某种原因parseFloat不会吗?

Any imput would be greatly appreciated, all the examples of code people made thusfar result in different numbers than i'm expecting. 任何输入都将不胜感激,到目前为止,人们编写的所有代码示例所产生的数字均与我预期的不同。

Unpacking a float from a word using DataView : 使用DataView从单词解压缩浮点数:

> v = new DataView(new ArrayBuffer(4))
> v.setUint32(0, 0x40e9b76a)
> v.getFloat32(0)
7.3036394119262695

(Recommended over Uint32Array and Float32Array because it does not inherit the platform's endianness.) (推荐使用Uint32ArrayFloat32Array因为它不继承平台的字节序。)

You could also use this to swap the two 16-bit units: 您还可以使用它来交换两个16位单元:

> v.setUint32(0, 0xb76a40e9)
> ((hi, lo) => {
    v.setUint16(0, hi);
    v.setUint16(2, lo);
  })(v.getUint16(2), v.getUint16(0))
> v.getUint32(0).toString(16)
'40e9b76a'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM