標籤:java 位元運算
位元運算:
~(非)——》位元進行0和1的互換
例子:
public class Test {public static void main(String[] args) {System.out.println(~-2);//輸出1System.out.println(~-1);//輸出0System.out.println(~0);//輸出-1System.out.println(~1);//輸出-2System.out.println(~2);//輸出-3System.out.println(~3);//輸出-4}}
^(異或)——》12 ^ 10 = ...01100^01010 = 00110 = 6
例子:
public class Test {public static void main(String[] args) {int a = 0;int b = 0;b = a = 12^10;System.out.println(a);//輸出為 6a = a^12;System.out.println(a);//輸出為 10b = b^10;System.out.println(b);//輸出為 12}}
應用:二個不同的數進行交換
public class Test {public static void main(String[] args) {int a = 12;int b = 10;System.out.println(a + "---" + b);// 輸出為12---10a = a ^ b;b = a ^ b;a = a ^ b;System.out.println(a + "---" + b);// 輸出為10---12}}
&(與)——》12 & 10 = ...01100 & 01010 = 01000 = 8
例子:
public class Test {public static void main(String[] args) {int a = 12;int b = 10;int c = a&b;System.out.println(c);//輸出為 8}}
應用:
public class Test {public static void main(String[] args) {int[] a = new int[2];a[0] = 5;a[1] = 6;for (int i = 0; i < a.length; i++) {if ((a[i] & 1) == 1) {// 判斷是否為奇數System.out.println(a[i] + "奇數");} else {System.out.println(a[i] + "偶數");}}// 輸出為:// 5"奇數"// 6"偶數"}}
|(或)——》12 | 10 = ...01100 | ...01010 = 01110 = 14
例子:
public class Test {public static void main(String[] args) {int a = 12;int b = 10;// ...01100 | ...01010 = 01110 = 14int c = a | b;System.out.println(c);// 輸出為14}}
應用:和位移一起運算可以打包成不同位元的整數
public class Test {public static void main(String[] args) {int a = 1;int b = 2;// 256 | 2 = ...01 0000 0000 | ...0010 = ...01 0000 0010 = 258int c = a << 8 | b;System.out.println(c);// 輸出為258}}
>>(右位移)——》12>>2 = 00...01100 >>2 = 00...00011 = 3
-1 >>>24 = 1111...111 >>>24 = 1111...1111 1111 = -1
>>>(無符號)——》 -1 >>> 24 = 1111...111 >>> 24 = 0000...1111 1111 = 255
public class Test {public static void main(String[] args) {int a = -1;// 1111...111 >>> 24 = 0000...1111 1111 = 255int b = a>>>24;System.out.println(b);// 輸出為255}}12>>2 = 00...01100 >>2 = 00...00011 = 3
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
java位元運算筆記