将打包的字符串字符串转换为Javascript中的浮点数组 [英] Converting a string of packed bytes into an array of floats in Javascript

查看:71
本文介绍了将打包的字符串字符串转换为Javascript中的浮点数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在python中,您可以创建一个字符串来表示数组的打包字节,例如:

I know that in python you can create an a string representing the packed bytes of an array doing something like such:

import numpy as np

np.array([1, 2], dtype=np.int32).tobytes() 
# returns '\x01\x00\x00\x00\x02\x00\x00\x00'

np.array([1, 2], dtype=np.float32).tobytes() 
# returns '\x00\x00\x80?\x00\x00\x00@'

它们可以使用 np.fromstring

当前,我的Javascript是接收一个编码为浮点数数组的打包字节字符串(即'\x00\x00\x80?\x00\x00\x00 @')我需要解码数组-最好的方法是什么?

Currently, my Javascript is receiving a string of packed bytes that encodes an array of floats (i.e. '\x00\x00\x80?\x00\x00\x00@') and I need to decode the array -- what is the best way to do this?

(如果它是一个整数数组,我想我可以使用文本编码提取字节,然后适当地相乘并相加...)

(if it were an array of ints I imagine I could use text-encoding to pull the bytes and then just multiply and add appropriately...)

谢谢,

推荐答案

首先,您必须将字符串转换为缓冲区,然后在其上创建 Float32Array 缓冲。 (可选)将其展开以创建普通的 Array

First, you have to convert a string into a buffer, and then create a Float32Array on that buffer. Optionally, spread it to create a normal Array:

str = '\x00\x00\x80?\x00\x00\x00@'

bytes = Uint8Array.from(str, c => c.charCodeAt(0))
floats = new Float32Array(bytes.buffer)

console.log(floats)

console.log([...floats]);

这篇关于将打包的字符串字符串转换为Javascript中的浮点数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆