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位,移動(dòng)過程中,高位會(huì)丟失

有符號(hào)數(shù)右移操作: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.

無符號(hào)數(shù)右移: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.

例子:

下面的例子顯示如何將一個(gè)int數(shù)組通過移位操作壓縮到一個(gè)int內(nèi)保存,其原理是在java語言中,int類型使用4 bytes來保存,因此對(duì)于需要壓縮的int數(shù)組,其中的每一個(gè)int值的大小不能超過255(2的8次方-1),因此這只是一個(gè)實(shí)例:

  int [] aRGB = {0x56, 0x78, 0x9A, 0xBC};   // 是用16進(jìn)制保存的4種顏色值
  int color_val = aRGB[3];   
  color_val = color_val | (aRGB[2] << 8);  // 為了壓縮,需要放置到color_val值的第二個(gè)字節(jié)位置上:將aRGB[2] 左移到第二個(gè)byte,同時(shí)與color_val進(jìn)行或操作,下面同理
  color_val = color_val | (aRGB[1] << 16);  
  color_val = color_val | (aRBG[0] << 24);

操作完的結(jié)果是56 78 9A BC

如果要從colorVal 還原為int數(shù)組,或者得到數(shù)組中的某個(gè)值,只需要對(duì)colorVal 進(jìn)行相應(yīng)的右移操作即可:

  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