6 c++ floating-point unsigned casting char
在c ++中将unsigned char数组转换为float数组的最佳方法是什么?
我现在有一个for循环如下
for (i=0 ;i< len; i++)
float_buff[i]= (float) char_buff[i];
Run Code Online (Sandbox Code Playgroud)
我还需要反转过程,即从unsigned char转换为float(float到8bit转换)
for (i=0 ;i< len; i++)
char_buff[i]= (unsigned char) float_buff[i];
Run Code Online (Sandbox Code Playgroud)
任何意见,将不胜感激
谢谢
我认为最好的方法是使用一个函数对象:
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); }
};
Run Code Online (Sandbox Code Playgroud)
其次是:
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>());
Run Code Online (Sandbox Code Playgroud)
这是最具可读性的,因为它说明了用英语完成的工作:使用静态转换将序列转换为不同的类型.未来的演员表可以在一行中完成.
您的解决方案几乎是最佳选择,但是,我会考虑切换到:
char_buff[i]= static_cast<unsigned char>(float_buff[i]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14711 次 |
| 最近记录: |