java位运算符详解
java位运算符详解,位运算符用于执行数字的各个位的操作。它们可以与任何整数类型(char、short、int 等)一起使用。它们在执行二叉索引树的更新和查询操作时使用。
现在让我们看一下 Java 中的每个位运算符:
1. 按位或 (|)
该运算符是二元运算符,用“|”表示。它返回输入值的逐位或,即,如果任一位为 1,则返回 1,否则显示 0。
例子:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise OR Operation of 5 and 7
0101
| 0111
________
0111 = 7 (In decimal)
2. 按位与 (&)
该运算符是二元运算符,用“&”表示。它返回输入值的逐位与,即如果两个位都为 1,则返回 1,否则显示 0。
例子:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise AND Operation of 5 and 7
0101
& 0111
________
0101 = 5 (In decimal)
3. 按位异或 (^)
该运算符是二元运算符,用“^”表示。它返回输入值的逐位异或,即如果对应的位不同,则为1,否则为0。
例子:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise XOR Operation of 5 and 7
0101
^ 0111
________
0010 = 2 (In decimal)
4.按位补码(~)
此运算符是一元运算符,用“~”表示。它返回输入值的反码表示,即所有位反转,这意味着它使每 0 变为 1,每 1 变为 0。
例子:
a = 5 = 0101 (In Binary)
Bitwise Complement Operation of 5
~ 0101
________
1010 = 10 (In decimal)
// Java program to illustrate
// bitwise operators
public class operators {
public static void main(String[] args)
{
// Initial values
int a = 5;
int b = 7;
// bitwise and
// 0101 & 0111=0101 = 5
System.out.println("a&b = " + (a & b));
// bitwise or
// 0101 | 0111=0111 = 7
System.out.println("a|b = " + (a | b));
// bitwise xor
// 0101 ^ 0111=0010 = 2
System.out.println("a^b = " + (a ^ b));
// bitwise not
// ~00000000 00000000 00000000 00000101=11111111 11111111 11111111 11111010
// will give 1's complement (32 bit) of 5 = -6
System.out.println("~a = " + ~a);
// can also be combined with
// assignment operator to provide shorthand
// assignment
// a=a&b
a &= b;
System.out.println("a= " + a);
}
}
输出
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5
// Demonstrating the bitwise logical operators
class GFG {
public static void main (String[] args) {
String binary[]={
"0000","0001","0010","0011","0100","0101",
"0110","0111","1000","1001","1010",
"1011","1100","1101","1110","1111"
};
// initializing the values of a and b
int a=3; // 0+2+1 or 0011 in binary
int b=6; // 4+2+0 or 0110 in binary
// bitwise or
int c= a | b;
// bitwise and
int d= a & b;
// bitwise xor
int e= a ^ b;
// bitwise not
int f= (~a & b)|(a &~b);
int g= ~a & 0x0f;
System.out.println(" a= "+binary[a]);
System.out.println(" b= "+binary[b]);
System.out.println(" a|b= "+binary);
System.out.println(" a&b= "+binary[d]);
System.out.println(" a^b= "+binary[e]);
System.out.println("~a & b|a&~b= "+binary[f]);
System.out.println("~a= "+binary[g]);
}
}
输出
a= 0011
b= 0110
a|b= 0111
a&b= 0010
a^b= 0101
~a & b|a&~b= 0101
~a= 1100
移位运算符(移位运算符)
移位运算符用于向左或向右移动数字的位,从而分别将数字乘以或除以 2。当我们必须将一个数字乘以或除以 2 时,可以使用它们。
语法:
number shift_op number_of_places_to_shift;
移位运算符的类型:
移位运算符进一步分为 4 种类型。这些是:
- 有符号右移运算符 (>>)
- 无符号右移运算符 (>>>)
- 左移运算符
- 无符号左移运算符 (<<<)
常见问题FAQ
- 程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
- 请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!