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?
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 (ie 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
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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.