Skip to content

Java 与运算 0xFF

ythy edited this page Nov 17, 2017 · 1 revision

A & 0xFF 的意思是是 A & 00000000 00000000 00000000 11111111 即取A的后8位

It's a so-called mask. The thing is, you get the RGB value all in one integer, with one byte for each component. Something like 0xAARRGGBB (alpha, red, green, blue). By performing a bitwise-and with 0xFF, you keep just the last part, which is blue. For other channels, you'd use:

int alpha = (rgb >>> 24) & 0xFF;
int red   = (rgb >>> 16) & 0xFF;
int green = (rgb >>>  8) & 0xFF;
int blue  = (rgb >>>  0) & 0xFF;

In the alpha case, you can skip & 0xFF, because it doesn't do anything; same for shifting by 0 in the blue case.

通过RGBA拼接ARGB值的范例:

  1. RGBA中的R值 buffer.get(offset) & 0xff , 左移位16, 得 00000000 XXXXXXXX 00000000 00000000
  2. RGBA中的G值 buffer.get(offset + 1) & 0xff , 左移位8, 和上一步结果|运算得 00000000 XXXXXXXX XXXXXXXX 00000000
  3. RGBA中的B值 buffer.get(offset + 2) & 0xff , 和上一步结果|运算得 00000000 XXXXXXXX XXXXXXXX XXXXXXXX
  4. RGBA中的A值 buffer.get(offset + 3) & 0xff , 左移位24位 和上一步结果|运算得 XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX
                            int pixel = 0;
                            pixel |= (buffer.get(offset) & 0xff) << 16;     // R
                            pixel |= (buffer.get(offset + 1) & 0xff) << 8;  // G
                            pixel |= (buffer.get(offset + 2) & 0xff);       // B
                            pixel |= (buffer.get(offset + 3) & 0xff) << 24; // A
                            bitmap.setPixel(j, i, pixel);

Clone this wiki locally