What is the meaning of & 0xff when separating RGB channels from an RGB image?

I have the following piece of code

for(int row=0; row<r; row++)
{
    for(int col=0; col<c; col++)
    {
        alphaPixels[row][col] = ((RGBarray[ii]>>24)&0xff);
        redPixels[row][col] = ((RGBarray[ii]>>16)&0xff);
        greenPixels[row][col] = ((RGBarray[ii]>>8)&0xff);
        bluePixels[row][col] = (RGBarray[ii]&0xff);
        ii++;
    }
}

      

Why should we use the bitwise AND & 0xff

operation after the switch operation?

+3


source to share


2 answers


Why should we use bitwise AND and 0xff operations after switching operation?

Oxff

is a hexadecimal number equal to decimal 255.

In your case, & 0xff

make sure that the entire range of pixel values โ€‹โ€‹is between 0 and 255 (i.e. positive 8 bits). For example, if any value is greater than 255, then it truncates it within the range 0-255



    int value=257;
    int result = value & 0xff; // result will be 1

      

Thus, it works like a %

positive remainder operator . But the bitwise operator &

is faster than the remainder operator %

.

    int result = value % 256; //You will get same result for positive value 

      

+2


source


0xff

has an integer value of 255.

>> n

on the right shifts the number of bits n

, the operator &

performs a bitwise AND operation.



So it & 0xff

masks the variable. It only leaves the last 8 bits and ignores all other bits.

This is a common trick when you are trying to convert color values โ€‹โ€‹from a custom format to standard RGB values โ€‹โ€‹(since it is 8 bits).

+1


source







All Articles