-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitOperation.java
More file actions
36 lines (33 loc) · 1.45 KB
/
BitOperation.java
File metadata and controls
36 lines (33 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.base;
/**
* @Author: lenovo
* @Date: 2018/12/3 11:27
* @Description:
* 无符号数a的左移相当于将该数用二进制表示,左移n位就是把最高位n位移出,低位添加n个0的操作,左移操作相当于将该数乘以2^n次方。
* 右移操作相当于将该数除以2^n次方。
*
*
* 位运算符先用二进制表示,再对每一位进行计算。
* &表示同时不为0,才是1。
* |表示只要有一个为1,就是1。
* ^表示相同则为0,不同则为1.
* ~表示取反。
*
*/
public class BitOperation {
public static void main(String[] args) {
System.out.println("位运算符:");
// 16用二进制表示是 10000,右移四位得到 1.
System.out.println("1左移4位结果为:"+(1<<4) );
System.out.println("16右移4位结果为:"+(16>>4) );
//2用二进制表示是10,而4用二进制表示是100.运算时,位数不足就补0.
// 010 & 100 , 对每一位进行运算, 结果得到 000
System.out.println("2&4结果为:"+(2&4));
// 010 | 100 , 对每一位进行运算, 结果得到 110
System.out.println("2|4结果为:"+(2|4));
// 010 ^ 100 , 对每一位进行运算, 结果得到 110
System.out.println("2^4结果为:"+(2^4));
// 非运算的结果比较复杂,涉及到"相反数"
System.out.println("~2结果为:"+(~2));
}
}