按位操作符
Java中最不常用的按位操作符。按位操作符有:&(與)、 |(或)、 ^(異或)、 ~(取反)。
具體含義和用法,我們直接上代碼。
用代碼解釋含義:
package com.cn.study;
//按位操作運算
public class BitOperationStudy {
/**
* & 按位與
* 如果兩個整型數據a、b對應爲都是1,則結果爲纔是1,否則爲0
*/
public static void and(int a, int b) {
int c = a & b;//相同位的兩個數字都爲1,則爲1;若有一個不爲1,則爲0。
System.out.println("a : " + a);
System.out.println("b : " + b);
System.out.println("c : " + c);//1
}
/**
* | 按位或
* 參與運算的兩數各對應的二進位相或。只要對應的二個二進位有一個爲1時,結果位就爲1
*/
public static void or(int a, int b) {
int c = a | b;//相同位的兩個數字若有一個爲1,則爲1,否則爲0。
System.out.println("a : " + a);
System.out.println("b : " + b);
System.out.println("c : " + c);//1
}
/**
* ^ 按位異或
* 參與運算的兩數各對應的二進位相異或,當兩對應的二進位相異時,結果爲1
* @param a
* @param b
*/
public static void xor(int a, int b) {
int c = a ^ b;//相同位的兩個數字對應的二進位相異時,結果爲1。
System.out.println("a : " + a);
System.out.println("b : " + b);
System.out.println("c : " + c);//1
}
/**
* ~取反
* 參與運算的兩數如果位爲0,結果是1,如果位爲1,結果是0.
* @param a
*/
public static void negation(int a) {
int c = ~a;//如果位爲0,結果是1,如果位爲1,結果是0.
System.out.println("a : " + a);
System.out.println("c : " + c);//1
}
// <<左移 位移操作符,暫無示例
// >>右移 位移操作符,暫無示例
public static void main(String[] args) {
//與 &
and(9, 3);//9=1001 3=0011 &對應爲:0001
and(8, 5);//8=1000 5=0101 &對應爲:0000
//或 |
or(9, 3);//9=1001 3=0011 |對應爲:1011=11
or(8, 5);//8=1000 5=0101 |對應爲:1101=13
// ^ 按位異或
xor(9, 3);//9=1001 3=0011 ^對應爲:1010=10
xor(8, 5);//8=1000 5=0101 ^對應爲:1101=13
// ~ 按位取反
negation(9);//9=1001 ~對應爲:0110=6
negation(5);//5=0101 ~對應爲:1010=10
}
}
輸出結果和運算解析
a : 9
b : 3
c : 1
a : 8
b : 5
c : 0
a : 9
b : 3
c : 11
a : 8
b : 5
c : 13
未完,有待補充。位移操作符