Doubt about operator in c ++

1

I'm starting to work with bmp images in c ++ and there is some operator that I can not understand how it works, basically these are: string str string

#include <cstdio>
#include <cstring>

void ocultar(BMP & bmp, char * str){
 int pixelsRequeridos = (1 + strlen(str)) * 8; 
 if (pixelsRequeridos <= bmp.nPixels)
 {
    char * pixel;
    for (pixel = bmp.pixels; *str; str++)
    {
        for (int i = 0; i < 8; i++, *pixel++)
        {
            char bit = ((*str) >> i) & 1; //Operador que no entiendo
            if(bit)
                *pixel |= 1;    //Operador que no entiendo
            else
                *pixel &= 0xfe; //Operador que no entiendo    
        }
    }
    for (int i = 0; i < 8; i++, *pixel++)  
        *pixel &= 0xfe;
 }

}

    
asked by Arzu15 11.05.2017 в 12:50
source

1 answer

2
char bit = ((*str) >> i) & 1;

We are going to analyze it in parts:

  • *str - > the operator * serves to dereference a pointer, if you have char* the operator * allows you to access the char referenced by the pointer.
  • X >> i - > the operator >> is, in this case, a binary bit shift operator. What it does is move to the right the bits of the variable X , which in your case is *str . What is the bit offset? I show you a simple example:

    11 >> 2 = 2 => 01011 >> 2 = 00010
    
  • Y & 1 - > the operator & performs an AND operation bit level:

    11 & 7 = 3 => 01011 & 00111 = 00011
    

More little things:

if(bit)
    *pixel |= 1;    //Operador que no entiendo
else
    *pixel &= 0xfe; //Operador que no entiendo

Let's see:

The operator | is an OR operator at the bit level:

11 | 6 = 15 => 01011 | 00110 = 01111

And the operator |= is an alias of the following:

*pixel = *pixel | 1;

On the other hand, the operator & we have seen before, performs an AND operation at bit level. And the operator &= does the same as the operator |= but with an AND operation. That is, that instruction would be equivalent to:

*pixel = *pixel & 0xfe
    
answered by 11.05.2017 / 15:15
source