Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the significance of &0xff while separiting the RGB channels out from an RGB image?

I have the following code snippet

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 do we have to use the bitwise AND operation & 0xff after the shifting operation?

like image 965
Rohit S Avatar asked Nov 22 '25 04:11

Rohit S


2 Answers

Why do we have to use the bitwise AND operation ' & 0xff' after the shifting operation?

Oxff is hexadecimal number which is equal to decimal 255.

In your case, & 0xff ensure all pixel values range be within 0 to 255 (i.e. positive 8 bit). For example, if any value is greater than 255 than it will truncated it within 0-255

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

So, it works like remainder operator % of positive value. But bitwise operator & is more faster than remainder operator %.

    int result = value % 256; //You will get same result for positive value 
like image 127
Masudul Avatar answered Nov 24 '25 17:11

Masudul


0xff has integer value of 255.

>> n right shifts the number n bits, & operator performs a bitwise AND operation.

So & 0xff masks the variable. It leaves only the value in the last 8 bits, and ignores all the rest of the bits.

This is a common trick when you try to transform color values from a special format to standard RGB values (since it has 8-bits).

like image 45
Maroun Avatar answered Nov 24 '25 17:11

Maroun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!