PPM 将字符转换为 int 授予负数

PPM conversion char to int grants negative numbers

本文关键字:int 字符 转换 PPM      更新时间:2023-10-16

我的任务是将字符从 PPM 图片转换为 int 数组,然后在该数组上进行其他转换。我得到了公式,它应该将 PPM 文件中的 3 个字符(文件中的红色、绿色和蓝色顺序(转换为一个 int 变量

int main(){
ifstream obraz1;
obraz1.open("start_1.ppm", ios::in);
int x,y,colors;
char proba[10000];
string firstline; //P6
getline(obraz1,firstline); //p6 scan
//
string line;
getline(obraz1,line);
sscanf(line.c_str(),"%d %dn",&x,&y);
getline(obraz1,line);
sscanf(line.c_str(),"%dn",&colors);
int lenghtwithoutheader=obraz1.tellg();
cout<<firstline<<" "<<endl;
cout <<x<<" "<<y<<" "<<" "<<colors<<endl;
/////////////////LOAD////////////////////////
int length;
obraz1.seekg(0, std::ios::end); 
length = obraz1.tellg();           // report location (this is the length)
obraz1.seekg(lenghtwithoutheader, ios::beg);    
char* buffor;
cout<<"full pic: "<<length<<"pic without head : "<<lenghtwithoutheader<<endl;
buffor = new char[length-lenghtwithoutheader];
obraz1.read(buffor,length-lenghtwithoutheader);

int *tabobraz=new int[(length-lenghtwithoutheader)/3];
for(int i=0;i<length-lenghtwithoutheader;i=i+3){
tabobraz[i]=(buffor[i]*(256*256))+(buffor[i+1]*256)+buffor[i+2];
cout<<"to int "<<(int)buffor[i]<<" "<<(int)buffor[i+1]<<" "<<(int)buffor[i+2]<<" "<<endl;
cout<<i<<" "<<buffor[i]<<" "<<buffor[i+1]<<" "<<buffor[i+2]<<" "<<endl;

}

return 0;
}

不知何故,我最终得到了负数(这对于图片来说是不可能的(:

to int 112 -72 -18
2247 p Ş ţ

我的第一个想法是,也许我不知何故溢出了 int 并且它又回到了负数,但这是不可能的,我可以使用该数字的最大字节数是 16-20 个字节中的 32 个字节。我在不同的系统和硬件上测试了它,所以我认为这不是那么重要。我怎样才能让它工作?

问题是char在您的实现上签名(char的签名是特定于实现的(。

读取以下内容时使用无符号缓冲区和强制转换:

unsigned char* buffor = new unsigned char[length - lenghtwithoutheader];
obraz1.read(reinterpret_cast<char*>(buffor), length - lenghtwithoutheader);