Created
October 28, 2022 15:26
-
-
Save XDo0/a055137e40c9ef712c84ffc285c93bcb to your computer and use it in GitHub Desktop.
Java bitwise operation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int n = 4; | |
// 移位运算(注意溢出情况!) | |
int n1 = n << 1; // 这里相当于*2,n1:0b1000, 8 | |
int n2 = n >> 2; // n2: 0b1, 1 | |
// 与 | |
int n3 = n & 2; | |
// 或 | |
int n4 = n | 2; | |
// 取反/非 | |
int n5 = ~ n; | |
// 异或 | |
int n6= n ^ 2; | |
// 计算n的位数,比如4是0b100,位数是3 | |
int bitCount = 0; | |
while (n>0) { | |
n=n>>1; | |
bitCount++; | |
} | |
// 综合应用 | |
int x = 2; | |
for (int bit = 0; bit < bitCount; bit++) { | |
// 0b1,0b10,0b100与计算!=0 | |
// 判断某一位是否是1 | |
if (n & (1 << bit))!=0) { | |
System.out.println("该位是1"); | |
} | |
// 或运算将对应位赋值为1 | |
x |= (1 << bit); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment