python uint8转float_直接转换numpy的unit8原料阵列FLOAT32

In my situation I get a numpy.ndarray as unit8 of size 4 * n which represents raw binary data of float32 entities. So 4 items together represent one float32. To get float32 numbers I currently convert uint8 raw data to a binary string and than read from this string the float32 values.

np.fromstring(raw_unit8_data.tostring(), dtype='

Is there a possibility to do this conversion directly without converting the uint8 data to a string first?

解决方案

You could use view to have NumPy reinterpret the raw data as the appropriate data type. For example:

>>> raw_unit8_data = np.array([32, 14, 135, 241], dtype='uint8')

>>> raw_unit8_data.view('

array([ -1.33752168e+30], dtype=float32)

This has the advantage of not using any temporary arrays or buffers (we're just changing how the memory is read) and gives the same values as your current method:

>>> np.fromstring(raw_unit8_data.tostring(), dtype='

array([ -1.33752168e+30], dtype=float32)

要将Float32MultiArray转换为uint8_t,你需要进行以下步骤: 1. 获取Float32MultiArray的数据:首先,你需要获取Float32MultiArray中的数据。Float32MultiArray是一个多维数组,你可以通过访问其data属性来获取数据。 2. 进行数据类型转换:将Float32类型的数据转换为uint8_t类型。由于Float32的范围是-1到1之间,而uint8_t的范围是0到255之间,你需要将Float32的值映射到uint8_t的范围内。可以使用以下公式进行转换: uint8_t_value = (float_value + 1) * 127.5 3. 创建uint8_t数组:根据转换后的值,创建一个uint8_t类型的数组,并将转换后的值存储在数组中。 下面是一个示例代码,演示了如何将Float32MultiArray转换为uint8_t: ```cpp #include <iostream> #include <vector> #include <stdint.h> // 假设Float32MultiArray为float类型的多维数组 class Float32MultiArray { public: std::vector<float> data; }; std::vector<uint8_t> convertFloat32MultiArrayToUint8(const Float32MultiArray& floatArray) { std::vector<uint8_t> uint8Array; for (const auto& floatValue : floatArray.data) { uint8_t uint8Value = static_cast<uint8_t>((floatValue + 1) * 127.5); uint8Array.push_back(uint8Value); } return uint8Array; } int main() { Float32MultiArray floatArray; floatArray.data = {0.1, 0.5, -0.3, 0.8}; std::vector<uint8_t> uint8Array = convertFloat32MultiArrayToUint8(floatArray); for (const auto& uint8Value : uint8Array) { std::cout << static_cast<int>(uint8Value) << " "; } std::cout << std::endl; return 0; } ``` 这段代码将Float32MultiArray中的数据转换为uint8_t类型,并打印出转换后的结果。你可以根据自己的需求进行修改和使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值