title: Create/Save PPM-File from unsigned char* AND unsigned short* Pointers (RGB) (C++)
body: <p>I need help saving a PPM file in C/C++. I want to save an PPM image from the three basic color channels. The channels are represented as void * pointers (pRed, pGreen and pBlue). Those values are fixed so I cannot change them.</p>
  
  <p>There is one more variable to decide how the void pointer has to be interpreted:
  this variable is:</p>
  
  <p>bpp=1 the correct type is unsigned char *. Buffer elements are of type unsigned char</p>
  
  <p>bpp=2 the correct type is unsigned short *. Buffer elements are of type unsigned short.</p>
  
  <p>Now I would save an ppm file out of this three color channels. </p>
  
  <p>The declarations regarding to the bpp variable are:</p>
  
  <pre><code>//bpp=1:
  unsigned char* dRed = (unsigned char*)pImg-&gt;pRed;
  unsigned char* dGreen = (unsigned char*)pImg-&gt;pGreen;
  unsigned char* dBlue = (unsigned char*)pImg-&gt;pBlue;
  unsigned char* dBw = (unsigned char*)pImg-&gt;pBw;
  
  //bpp=2:
  unsigned short* dRed = (unsigned short*)pImg-&gt;pRed;
  unsigned short* dGreen = (unsigned short*)pImg-&gt;pGreen;
  unsigned short* dBlue = (unsigned short*)pImg-&gt;pBlue;
  unsigned short* dBw = (unsigned short*)pImg-&gt;pBw;
  </code></pre>
  
  <p>My code to write the ppm file:</p>
  
  <pre><code>ofstream output(fname, ios::binary|ios::out);
  
  output &lt;&lt; "P3"&lt;&lt; endl &lt;&lt;"# foreground "&lt;&lt;endl;
  output &lt;&lt; itoa(width, fname, 10);
  output &lt;&lt; " ";
  output &lt;&lt; itoa(height, fname, 10);
  output &lt;&lt; endl;
  output &lt;&lt; itoa(255, fname, 10) &lt;&lt; endl;
  ...     
  for(int i=0; i&lt;(height*width); i++){
    if(bytesPerP==1){
      output &lt;&lt; (unsigned char)((char*)dRed) &lt;&lt; " ";
      output &lt;&lt; (unsigned char)((char*)dGreen) &lt;&lt; " ";
      output &lt;&lt; (unsigned char)((char*)dBlue) &lt;&lt; " ";
      dRed = dRed + (i * bytesPerP);
      dGreen = dGreen + (i * bytesPerP);
      dBlue = dBlue + (i * bytesPerP);
  }else if(bytesPerP==2){
      output &lt;&lt; ((unsigned short)((char*)dRed))%256 &lt;&lt; " ";
      output &lt;&lt; (unsigned short)((char*)dGreen)%256 &lt;&lt; " ";
      output &lt;&lt; (unsigned short)((char*)dBlue)%256 &lt;&lt; " ";
  
      dRed = dRed + (i * bytesPerP);
      dGreen = dGreen + (i * bytesPerP);
      dBlue = dBlue + (i * bytesPerP);
  }
  </code></pre>
  
  <p>Here is anywhere the error, because i get the right "structure" of the recorded image, but the colors are totally weird (psychodelic style) :)
  I have searched on the internet and tested many things, but none of them worked. Could someone point me in the right direction?</p>