Thursday, 26 April 2018

Core Java: Bitwise Logical Operator

Bitwise operators perform operations on one or two operands on a bit-by-bit basis, as follows, in descending order of precedence.
 
Operator
Description
Usage
~
Bitwise NOT (inversion)
~expr
&
Bitwise AND
expr1 & expr2
^
Bitwise XOR
expr1 ^ expr2
|
Bitwise OR
expr1 | expr2

Expr1
Expr2
Expr1|Expr2
Expr1& Expr2
Expr1^ Expr2
False
False
False
False
False
False
True
True
False
True
True
False
True
False
True
True
True
True
True
False


For ~ operator

~n   -----> - (n+1)
 
Example
 
public class TestBitwiseOp {
   public static void main(String[] args) {
      int x = 0xAAAA_5555;                // a negative number (sign bit (msb) = 1)
      int y = 0x5555_1111;                // a positive number (sign bit (msb) = 0)
      System.out.printf("%d%n", x);       // -1431677611
      System.out.printf("%d%n", y);       // 1431638289
      System.out.printf("%08X%n", ~x);    // 5555AAAAH
      System.out.printf("%08X%n", x & y); // 00001111H
      System.out.printf("%08X%n", x | y); // FFFF5555H
      System.out.printf("%08X%n", x ^ y); // FFFF4444H
   }
}
 
Compound operator &=, |= and ^= are also available, e.g., x &= y is the same as x = x & y. 
 
Take note that:
 
·        '&', '|' and '^' are applicable when both operands are integers (int, byte, short, long and char) or booleans. When both operands are integers, they perform bitwise operations. When both operands are booleans, they perform logical AND, OR, XOR operations (i.e., same as logical &&, || and ^). They are not applicable to float and double. On the other hand, logical AND (&&) and OR (||) are applicable to booleans only. 
 
·        System.out.println(true & true);   // logical -> true
 
·        System.out.println(0x1 & 0xffff);  // bitwise -> 1
 
·        System.out.println(true && true);  // logical -> true
 
·        The bitwise NOT (or bit inversion) operator is represented as '~', which is different from logical NOT (!).
 
·        The bitwise XOR is represented as '^', which is the same as logical XOR (^).
 
·        The operators' precedence is in this order: '~', '&', '^', '|', '&&', '||'. 
For example, 
 
      System.out.println(true | true & false);  // true | (true & false) -> true
System.out.println(true ^ true & false);  // true ^ (true & false) -> true

No comments:

Post a Comment

Please write your view and suggestion....