咸鱼

咸鱼是以盐腌渍后,晒干的鱼

0%

Java、Kotlin位运算

一、位运算

左移1位

1
2
3
4
5
//java:
int a = num << 1;

//kotlin
val a: Int = num shl 1

右移1位

1
2
3
4
5
//java:
int a = num >> 1;

//kotlin
val a: Int = num shr 1

二、使能位

1
2
3
4
5
6
// 按位赋值
//java
int a = num | (0x01 << i);

//kotlin
val a: Int = num or (0x01 shl i)

利用位运算,可以简单的实现多个“使能位”,比如用一个Int类型就可以一个月的日期(31位)使能。

1
2
3
4
5
6
7
8
9
10
11
12
13
//java
int value = 0x00;
for (int i = 0; i < 31; i++) {
// if(i % 2 == 0){
// value |= 0x01 << i;
// }

if(i == 5 || i == 30){
value |= 0x01 << i;
}
}
System.out.println(value);
System.out.println(Integer.toBinaryString(value));
1
2
3
4
5
6
7
8
9
10
11
12
13
//kotlin
var value = 0x00
for (i in 0..30) {
if (i % 2 == 0) {
value = value or (0x01 shl i)
}

// if (i == 5 || i == 30) {
// value = value or (0x01 shl i)
// }
}
println(value)
println(Integer.toBinaryString(value))

if(i % 2 == 0) 运行结果:

1
2
1431655765
1010101010101010101010101010101

if(i == 5 || i == 30) 运行结果:

1
2
1073741856
1000000000000000000000000100000

三、取使能位

同样通过位运算可以取出任意位置的“使能位”

1
2
3
4
5
6
// 取位
//java
int a = (num >> i) & 0x01;

//kotlin
val a: Int = num shr i and 0x01

举例:

1
2
3
4
5
6
7
8
//java
int day = 1073741824; //1000000000000000000000000000000
System.out.println(Integer.toBinaryString(day));
for (int i = 0; i < 31; i++) {
//取位
int mbit = (day >> i) & 0x01;
System.out.println(i + " -> " + mbit);
}
1
2
3
4
5
6
7
8
//kotlin
val day = 59 //0000000000000000000000000111011
println("day: ${Integer.toBinaryString(day)}" )
for (i in 0..30){
//取位
val mbit = (day shr i and 0x01)
println("$i -> $mbit")
}

day = 59 运行结果:

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
111011
0 -> 1
1 -> 1
2 -> 0
3 -> 1
4 -> 1
5 -> 1
6 -> 0
7 -> 0
8 -> 0
9 -> 0
10 -> 0
11 -> 0
12 -> 0
13 -> 0
14 -> 0
15 -> 0
16 -> 0
17 -> 0
18 -> 0
19 -> 0
20 -> 0
21 -> 0
22 -> 0
23 -> 0
24 -> 0
25 -> 0
26 -> 0
27 -> 0
28 -> 0
29 -> 0
30 -> 0

day = 1073741824 运行结果:

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
1000000000000000000000000000000
0 -> 0
1 -> 0
2 -> 0
3 -> 0
4 -> 0
5 -> 0
6 -> 0
7 -> 0
8 -> 0
9 -> 0
10 -> 0
11 -> 0
12 -> 0
13 -> 0
14 -> 0
15 -> 0
16 -> 0
17 -> 0
18 -> 0
19 -> 0
20 -> 0
21 -> 0
22 -> 0
23 -> 0
24 -> 0
25 -> 0
26 -> 0
27 -> 0
28 -> 0
29 -> 0
30 -> 1