【问题标题】:PPM conversion char to int grants negative numbersPPM 将 char 转换为 int 授予负数
【发布时间】: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 change int *taboobraz `` 到无符号,我仍然得到错误的数字(因为我再次溢出 int ) 但没有 ``` - ``` 符号

标签: c++ ppm


【解决方案1】:

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

阅读时使用无符号缓冲区并强制转换:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    相关资源
    最近更新 更多