在緩衝器1和緩衝器的值不能是相同的或者它會工作。也許你在printf命令中使用的格式掩蓋了差異(%i,%f等)。不要使用printf,請嘗試設置斷點並使用調試器查看值。這可能有助於揭示實際發生了什麼問題。
編輯:
鑑於你關於你如何執行轉換的意見,我覺得我現在可以提供幫助。原始數據是unsigned char類型。在大多數平臺上,這將是一個介於0和255之間的整數值。您希望將此值轉換爲浮點數來執行操作。爲了使數據對於任何操作都具有浮點類型的意義,您希望將該範圍縮放到+/- 1.0之間。這是以下代碼中「scale」變量的用處。
#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
你好,謝謝你的回答。我在古典中扮演角色,我認爲:for(i = 0; i
victor
2012-03-30 08:12:06
當我比較buffer1 [i]和buffer [2]值時,它們不相等(buffer2 [i]大於buffer2 [i]) – victor 2012-03-30 08:57:16