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