buffer1 和 buffer2 中的值不能相同,否则会起作用。也许您在 printf 命令中使用的格式会掩盖差异(%i、%f 等)。不要使用 printf,而是尝试设置断点并使用调试器查看值。这可能有助于揭示实际出了什么问题。
编辑:
鉴于您对演员表演方式的评论,我想我现在可以提供帮助。传入的原始数据是无符号字符类型。在大多数平台上,这将是一个介于 0 和 255 之间的整数值。您希望将此值转换为浮点数以进行操作。要使数据作为浮点类型对任何操作都有意义,您希望在 +/- 1.0 之间缩放此范围。这就是以下代码中“比例”变量的用途。
#include <iostream>
#include <math.h>
int main()
{
const int BUFFER_LEN = 6;
const unsigned char channelDataIN[] = {0,255, 1, 254, 2, 253};
unsigned char channelDataOUT[BUFFER_LEN];
float channelDataF[BUFFER_LEN];
std::cout.precision(5);
float scale = powf(2.f, 8.f*sizeof(unsigned char) ) - 1.f;
for (int mm = 0; mm < BUFFER_LEN; ++mm)
{
std::cout << "Original = " << (int)channelDataIN[mm] << std::endl;
channelDataF[mm] = (float)(channelDataIN[mm]) * 2.f/scale - 1.f; //Float cast
std::cout << "Float conversion = " << channelDataF[mm] << std::endl;
channelDataOUT[mm] = (unsigned char) ceil( ( 1.f+channelDataF[mm] ) * scale/2.f );
std::cout << "Recovered = " << (int)channelDataOUT[mm] << std::endl;
if (channelDataIN[mm] == channelDataOUT[mm])
std::cout << "The output precisely equals the input" << std::endl << std::endl;
else
std::cout << "The output != input" << std::endl << std::endl;
}
return 0;
}
将值转换回后的无符号字符输出数组与输入数组相同。这是代码的输出。. .
Original = 0
Float conversion = -1
Recovered = 0
The output precisely equals the input
Original = 255
Float conversion = 1
Recovered = 255
The output precisely equals the input
Original = 1
Float conversion = -0.99216
Recovered = 1
The output precisely equals the input
Original = 254
Float conversion = 0.99216
Recovered = 254
The output precisely equals the input
Original = 2
Float conversion = -0.98431
Recovered = 2
The output precisely equals the input
Original = 253
Float conversion = 0.98431
Recovered = 253
The output precisely equals the input