7

在 C++ 中将无符号字符数组转换为浮点数组的最佳方法是什么?

我目前有一个for循环如下

for (i=0 ;i< len; i++)
    float_buff[i]= (float) char_buff[i];

我还需要反转过程,即从无符号字符转换为浮点数(浮点数到8位转换)

for (i=0 ;i< len; i++)
    char_buff[i]= (unsigned char) float_buff[i];

任何意见,将不胜感激

谢谢

4

8 回答 8

10

我认为最好的方法是使用函数对象:

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>());

这是最易读的,因为它用英语说明了正在做的事情:使用静态转换将序列转换为不同的类型。未来的演员阵容可以在一行中完成。

于 2009-05-05T16:47:50.903 回答
8

Your solution is pretty much the best option, however, I would consider switching to:

char_buff[i]= static_cast<unsigned char>(float_buff[i]);
于 2009-05-05T15:18:17.827 回答
2

For what purpose are you doing this? Shoving a float into a char doesn't really make sense. On most platforms a float will be 4 bytes and represent a floating point number, where as a char will be 1 byte and often represents a single character. You'll lose 3 bytes of data trying to shove a float into a char, right?

于 2009-05-05T15:17:54.130 回答
2

您的第一个循环不需要演员表。您可以从一种类型(例如 )隐式转换unsigned char为更广泛的类型(例如float)。你的第二个循环应该使用static_cast

for (i=0; i< len; i++)
    char_buff[i]= static_cast<unsigned char>(float_buff[i]);

我们使用static_cast显式告诉编译器将转换为更窄的类型。如果您不使用强制转换,您的编译器可能会警告您转换可能会丢失数据。演员表操作员的存在意味着您了解您可能会丢失数据精度并且您可以接受。这不是一个合适的地方使用reinterpret_cast。使用static_cast,您至少对可以进行的转换有一些限制(例如,它可能不允许您将 a 转换Bird*为 a Nuclear_Submarine*)。 reinterpret_cast没有这样的限制。

此外,这也是Bjarne Stroustrup对这个主题的看法。

于 2009-05-05T16:07:24.653 回答
2

演员表是自动的,因此您无需明确说明。
但是您可以使用标准算法:

std::copy(char_buff,char_buff+len,float_buff);

从 float 转换回 char 可能会丢失信息。所以你需要更明确。

std::transform(float_buff,float_buff+len,char_buff,MyTransform());

这里我们使用 MyTransform 类,它应该有一个 operator(),它接受一个浮点数并返回一个字符。这应该是微不足道的。

于 2009-05-05T16:51:46.980 回答
2

您的解决方案似乎是正确的,但在返回的路上,您可能会丢失铸造中的浮动数字。

于 2009-05-05T15:15:55.277 回答
0

If you are dealing with very large arrays and performance is essential then the following may prove slightly more efficient:

   float *dst = float_buff;
   unsigned char *src = char_buff;

   for (i=0; i<len; i++) *dst++ = (float)*src++;
于 2009-05-05T15:22:31.577 回答
0

没有人提到这一点,但如果你对浮点数进行任何算术运算,你可能想要舍入而不是截断......如果你有 char 49,它会变成 4.9E1,经过一些算术,它可能变成 4.89999999E1 当你把它变成一个字符时它会变成 48。

如果你没有对浮点数做任何事情,这应该不是问题,但是你为什么首先需要它作为浮点数呢?

于 2009-05-05T18:29:40.833 回答