java 位操作符:

取反:~x
- flips each bit to the opposite value.

与操作:AND

x & y
- AND operation between the corresponding bits in x and y.

或操作:OR
x | y
- OR operation between the corresponding bits in x and y.

异或操作:XOR
x ^ y
- XOR operation between the corresponding bits in x and y.

左移操作:Shift left
x << y
- shifts x to the left by y bits. The high order bits are lost while zeros fill the right bits.

将x左移y位,移动过程中,高位会丢失

有符号数右移操作:Shift Right - Signed
x >> y
- shifts x to the right by y bits. The low order bits are lost while the sign bit value (0 for positive numbers, 1 for negative) fills in the left bits.

无符号数右移:Shift Right - Unsigned
x >>> y
- shifts x to the right by y bits. The low order bits are lost while zeros fill in the left bits regardless of the sign.

例子:

下面的例子显示如何将一个int数组通过移位操作压缩到一个int内保存,其原理是在java语言中,int类型使用4 bytes来保存,因此对于需要压缩的int数组,其中的每一个int值的大小不能超过255(2的8次方-1),因此这只是一个实例:

  int [] aRGB = {0x56, 0x78, 0x9A, 0xBC};   // 是用16进制保存的4种颜色值
  int color_val = aRGB[3];   
  color_val = color_val | (aRGB[2] << 8);  // 为了压缩,需要放置到color_val值的第二个字节位置上:将aRGB[2] 左移到第二个byte,同时与color_val进行或操作,下面同理
  color_val = color_val | (aRGB[1] << 16);  
  color_val = color_val | (aRBG[0] << 24);

操作完的结果是56 78 9A BC

如果要从colorVal 还原为int数组,或者得到数组中的某个值,只需要对colorVal 进行相应的右移操作即可:

  int alpha_val = (colorVal >>> 24) & 0xFF;
  int red_val   = (colorVal >>> 16) & 0xFF;
  int green_val = (colorVal >>>  8) & 0xFF;
  int blue_val  =  colorVal & 0xFF;

参考资料:

Bits in Java