将无符号字符数组转换为浮点数组 [英] Casting an array of unsigned chars to an array of floats
本文介绍了将无符号字符数组转换为浮点数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在c ++中将无符号char数组转换为float数组的最佳方法是什么?
What is the best way of converting a unsigned char array to a float array in c++?
我目前有如下的for循环
I presently have a for loop as follows
for (i=0 ;i< len; i++)
float_buff[i]= (float) char_buff[i];
我还需要逆转该过程,即从无符号字符转换为浮点数(将浮点数转换为8bit)
I also need to reverse the procedure, i.e convert from unsigned char to float (float to 8bit conversion)
for (i=0 ;i< len; i++)
char_buff[i]= (unsigned char) float_buff[i];
任何建议将不胜感激
谢谢
推荐答案
我认为最好的方法是使用函数对象:
I think the best way is to use a function object:
template <typename T> // T models Any
struct static_cast_func
{
template <typename T1> // T1 models type statically convertible to T
T operator()(const T1& x) const { return static_cast<T>(x); }
};
其后为:
std::transform(char_buff, char_buff + len, float_buff, static_cast_func<float>());
std::transform(float_buff, float_buff + len, char_buff, static_cast_func<unsigned char>());
这是最易读的,因为它说的是英语:将序列转换为其他使用静态强制类型输入。而且将来的转换可以在一行中完成。
This is the most readable because it says what is being done in English: transforming a sequence into a different type using static casting. And future casts can be done in one line.
这篇关于将无符号字符数组转换为浮点数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文