數字圖像處理的作業中要讀取一個二進制文件。所有的灰度值爲0-255. 使用下面的方法讀取時出現了問題。
ifstream fin;
fin.open("data_batch_1.bin",ios::binary);
if(!fin){
cout<<"open error!"<<endl;
return -1;
}
char buffer[3073];
fin.read(buffer,3073*sizeof(char));
for(int i=0;i<17;i++){
cout<<(unsigned short)buffer[i]<<endl;
}
由於char是有符號的,因此在使用unsigned short進行轉化的時候,也會出現問題。可以改爲下面的代碼。
ifstream fin;
fin.open("data_batch_1.bin",ios::binary);
if(!fin){
cout<<"open error!"<<endl;
return -1;
}
char buffer[3073];
fin.read(buffer,3073*sizeof(char));
for(int i=0;i<17;i++){
unsigned char tmp=(unsigned char)buffer[i];
cout<<(unsigned short)tmp<<endl;
}