java 位操作 bitwise(按位) operation bit
// 8 0000 0000 0000 1000 原码
1111 1111 1111 0111 反码
+ 1
1111 1111 1111 1000 (8的补码)来表示 -8
// -8 1111 1111 1111 1000 65528 补码(正值 的反码+1)
// 65535 1111 1111 1111 1111 65535
// 65535-65528=7+1=8
操作longValue = longValue | (1 << n); 可以在longValue的2进制表示中,把从右边数到左边数第n + 1位的值设置为1,并且不影响其他位上面的值 即用0和2进制值变量x做或|or操作,不会影响到2进制变量x的值
操作longValue = longValue & ~(1 << n); 可以在longValue的2进制表示中,把从右边数到左边数第n + 1位设置为0,并且不影响其他位上面的值 即用1和2进制值变量x做与&and操作,不会影响到2进制变量x的值
操作System.out.println((longValue >> n & 1) == 1); 可以判断值longValue的2进制表示中,从右边数到左边第n + 1位的值是0false 还是1true
- public class bitOperation {
-
-
- public static void main(String[] args) {
-
- long longValue = 0;
-
- longValue = longValue | (1 << 0);
-
- System.out.println(Long.toBinaryString(longValue));
- longValue = longValue | (1 << 1);
-
- System.out.println(Long.toBinaryString(longValue));
- longValue = longValue | (1 << 4);
-
- System.out.println(Long.toBinaryString(longValue));
- longValue = longValue | (1 << 5);
-
- System.out.println(Long.toBinaryString(longValue));
- longValue = longValue | (1 << 6);
-
- System.out.println(Long.toBinaryString(longValue));
-
- String hex = Long.toBinaryString(longValue);
-
- System.out.println(hex);
-
- System.out.println(Integer.valueOf("1110011", 2));
-
- System.out.println(Long.toBinaryString(longValue >> 0));
-
- System.out.println(Long.toBinaryString(longValue >> 0 & 1));
-
- System.out.println(Long.toBinaryString(longValue >> 1));
-
- System.out.println(Long.toBinaryString(longValue >> 1 & 1));
-
- System.out.println((longValue >> 0 & 1) == 1);
-
- System.out.println((longValue >> 1 & 1) == 1);
-
- System.out.println((longValue >> 2 & 1) == 1);
-
- System.out.println((longValue >> 3 & 1) == 1);
-
- System.out.println((longValue >> 4 & 1) == 1);
-
- System.out.println((longValue >> 5 & 1) == 1);
-
- System.out.println((longValue >> 6 & 1) == 1);
-
- System.out.println((longValue >> 7 & 1) == 1);
-
-
- bitLogic();
-
- byteShift();
- }
-
-
- private static void byteShift() {
- byte a = 64, b;
- int i;
-
- i = a << 2;
- b = (byte) (a << 2);
-
-
- System.out.println("Original value of a: " + a);
-
- System.out.println("i and b: " + i + " " + b);
- System.out.println("\r\n");
- }
-
-
- private static void bitLogic() {
- String binary[] = { "0000", "0001", "0010", "0011", "0100", "0101",
- "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101",
- "1110", "1111"
-
- };
- int a = 3;
- int b = 6;
- int c = a | b;
- int d = a & b;
- int e = a ^ b;
- int f = (~a & b) | (a & ~b);
- int g = ~a & 0x0f;
-
-
- System.out.println(" a = " + binary[a] + " = " + a);
-
- System.out.println(" b = " + binary[b] + " = " + b);
-
- System.out.println(" a|b = " + binary[c] + " = " + c);
-
- System.out.println(" a&b = " + binary[d] + " = " + d);
-
- System.out.println(" a^b = " + binary[e] + " = " + e);
-
- System.out.println("~a&b|a&~b = " + binary[f] + " = " + f);
-
- System.out.println(" ~a = " + binary[g] + " = " + g);
- System.out.println("\r\n");
- }
- }