从 RGB 图像中分离出 RGB 通道时 &0xff 的意义是什么?

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

我有以下代码片段

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++;
    }
}

为什么要在移位运算后使用按位与运算& 0xff

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

Oxff是十六进制数,等于十进制的255。

对于您的情况,& 0xff 确保所有像素值范围都在 0 到 255 之间(即正 8 位)。例如,如果任何值大于 255,它将在 0-255

范围内截断
    int value=257;
    int result = value & 0xff; // result will be 1

因此,它的工作原理类似于正值的余数运算符 %。但是按位运算符 & 比取余运算符 % 更快。

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

0xff 的整数值为 255。

>> n 右移数字 n 位,& 运算符执行 按位 AND 运算。

所以& 0xff屏蔽了变量。它只保留最后 8 位的值,而忽略所有其余位。

当您尝试将颜色值从特殊格式转换为标准 RGB 值(因为它有 8 位)时,这是一个常见的技巧。