C++ last bit of an image

Hi guys, I've been trying to find out what's wrong with the code, g++ doesn't prompt any error but it doesn't do what I want it to do, and after looking at it over and over I can't find anything wrong with it. The code its quite simple:

I need to save the last bit of every position on the vector and to form a word, for example:
buffer[0] has 00110011
buffer[1] has 11000010

I need to get the last bit and form a letter every 8 bits to decode the sentence.

buffer is a dinamic vector that has the image info loaded on it, cadena is where I want to store the "decoded " letters


 void revelarPGM (char* &cadena,unsigned char buffer[]) { 
 int binario=0;			
 int j=0;	
 cadena=new char[50000];
 for (int i=0; i<262144; i++) {
     if((buffer&1)==0){ // HERE i use the AND operator to get the last bit, if it is
           binario=(binario<<1);  // A 0, i just shift once
     }else{   
	   binario=(binario<<1);  //IF it is a 1, i shift and add a 1 with the OR
  	   binario=(binario|1);    
     }
   if (i%7==0) {               // WHEN i get 8 bits i store the letter in cadena
          cadena[j]=binario;
          j++;
	  cout << binario << endl;
          binario=0;
  }
 }
 for (int i=0; i<300; i++)
cout << cadena;  // cout to see the words i stored.
delete [] cadena;
}	

I hope I made myself clear. The problem is I am getting rubbish. But everytime i look at the code, it seems alright to me.

edit: tried to edit the title since i forgot to add it was C++ but it wont allow me now.

The "(i%7==0)" is incorrect. It only works the first time i hits 7.

It should be

( ( ( i + 1 ) % 8 ) == 0 )

And not the parenthesis. I'm not sure about operator precedence between "+", "==", and "%".

Think of it as, "If the NEXT iteration is divisible by 8, reset to the next byte."

1 Like

Thanks a bunch, that was the problem. Now it works flawlessly.