【发布时间】:2019-11-23 14:11:10
【问题描述】:
我的任务是将字符从 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 %d\n",&x,&y);
getline(obraz1,line);
sscanf(line.c_str(),"%d\n",&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,它又回到了负数,但这是不可能的,我可以与该数字一起使用的最大字节数是 32 个 int 中的 16-20 个字节。我在不同的系统和硬件上对其进行了测试,所以我认为这无关紧要。我怎样才能让它工作?
【问题讨论】:
-
您是否尝试将缓冲区更改为
unsigned char* buffor;? -
然后我不能使用函数 ``` obraz1.read(buffor,length-lenghtwithoutheader);
. When i tried to changeint *taboobraz `` 到无符号,我仍然得到错误的数字(因为我再次溢出 int ) 但没有 ``` - ``` 符号