Wednesday, 4 July 2018

Bitwise Operators

Bitwise Operators in Java

Bitwise and Bitwise Shift operators in Java are powerful set of operators which allows you to manipulate bits on integral types like int, long, short, bytes and boolean data types in Java. Bit wise and Bit shift operators are among the fastest operator in Java but still many people are not familiar with bit wise and bit wise shift operations. Moreover these operators are strange looking operators that may look hard to understand. But the following article will help you understand what they are and how to use them.

Bitwise Operators are classified in to two categories

Bitwise Logical Operators

  • & (bitwise AND)
  • | (bitwise OR)
  • ~ (bitwise NOT)
  • ^ (bitwise XOR)

Bitwise Shit Operators

  • << (bitwise left shift)
  • >> (bitwise right shift)
  • >>> (bitwise unsigned right shift)
Along with these another set shorthand assignment operators are provided
  • &= (bitwise AND assignment)
  • |= (bitwise OR assignment)
  • ^= (bitwise XOR assignment)
  • <<= (bitwise left shift and assignment)
  • >>= (bitwise right shift and assignment)
  • >>>= (bitwise unsigned right shift and assignment)

The & Operator
              Bitwise AND operator works similar to logical AND operator (&&) and returns 1 if both operands are 1. Difference with bitwise AND and logical AND also known as short-circuit AND operator is that, logical AND operator applies only to boolean type. Also bitwise AND operator is denoted by singe & while short circuit AND operator is denoted by &&. If A represent 0010 and B represent 1010 then result of A&B would be 0010. 

         int a = 2; //0010
         int b = 4; //0100
         int  c=a&b; // the result is zero

& operator can be used in many cases for examples it can be used to check whether a number is even or odd. For integers we can simply check the rightmost bit (also called the least significant bit) to determine if the integer is odd or even. This is because when converting to base 10, the rightmost bit represents 20 or 1. When the rightmost bit is 1, we know that our number is odd since we're adding 1 to a bunch of powers of two which will always be even. When the rightmost bit is 0, we know our number will be even, since it simply consists of adding up a bunch of even numbers.


int num=36;
if (result==1)
       System.out.println("Odd number.");
        System.out.println("Even number.");

Bitwise OR operator is also similar to bitwise AND operator and applies to individual bits. It’s different than short-circuit OR operator, which is denoted by (||) and operates on boolean variable. Like other bitwise operator in Java, bitwise OR is only applicable to integral types.

int a = 2; //0010
int b = 4; //0100     
int c=a|b; // result is 6

Bitwise unary complement operator (~)
Bitwise unary complement operator changes bits from 0 to 1, or vice versa and can only be applied on integral types. It’s not applicable on boolean types. For example int variable contains 32 bits; Applying this operator to a value whose bit pattern is 0000 would change its pattern to 11111. 

Here is an example of bitwise unary complement operator in Java
int number = 2; //0010
System.out.println(" value of number before: " + number);
System.out.println(" value of number after negation: " + ~number);

value of number before: 2
value of number after negation: -3

Bitwise XOR operator (^)
Bitwise XOR operator is denoted by ^ and also work on individual bits. There is no short-circuit XOR operator in Java and result of bitwise XOR operator is XOR operation of individual bits. In short bitwise XOR operators will return 1 if both bits are different and return 0 if both bits are same.

int a = 2; //0010
int b = 4; //0100
System.out.println(" value of a XOR B in Java : " + (a^b) );

value of a XOR B in Java : 6

Bitwise XOR operator can be used to swap two numbers without using temp variables

        int a = 2; //0010 in binary
        int b = 4; //0100 in binary
        System.out.println("value of a and b before swapping, a: " + a +" b: " + b);
 //swapping value of two numbers without using temp variable and XOR bitwise operator    
        a = a^b; //now a is 6 and b is 4
         b = a^b; //now a is 6 but b is 2 (original value of a)
         a = a^b; //now a is 4 and b is 2, numbers are swapped
        System.out.println("value of a and b after swapping using 
                                                          XOR bitwise operation, a: " + a +" b: " + b);
Bitwise Shift operator

Java bitwise shift operators can be used to shift bit from one position to another on both left and right side in a number. Java provides three bit shift operator signed left shift operator "<<", signed right shift operator ">>" and unsigned right shift operator ">>>". Left shift operator with sign, shifts bit into left side and fill the empty place with zero, while right shift operator with sign, shifts the bit on right side and fills the empty place with value of sign bit.  For positive number it fills with zero and for negative numbers it fills with 1. On the other hand ">>>" right shift without sign operator will only shift the bit towards right without preserving sign of number. As per syntax of bitwise shift operator, left hand side of operand is the number whose bit needs to be shift and right hand side of operator is how many bits needs to shift.


int number = 8; //0000 1000
//left shifting bytes with 1 position
number = number<<1; //should be 16 i.e. 0001 0000
//equivalent of multiplication of 2
number = -8;
 //right shifting bytes with sign 1 position
number = number>>1; //should be 16 i.e. 0001 0000   
number = 8;
 //right shifting bytes without sign 1 position
 number = number>>>1; //should be 16 i.e. 0001 0000

Important points to remember while using bit shift operators in Java

  1. Smaller types like byte, short are promoted to int before applying bit shift operator in Java. This requires explicit casting on lower type of result.
  2. If number of shift positions exceeds with number of bits in a variable, then remainder operator is used to calculate effective bit movement. For example int variables contains 32 bit, and if you shift bits to 33 times, then its equivalent of shifting bits 33%32 or just 1 time. e.g. 8 >> 33 is equal to 8 >> 1 and this is true for all bit shift operators.
  3. Since bit shift operators can simulate divide by 2 and multiplied by 2 operation they can be used to implement fast multiplication and division but on the cost of readability as its difficult to comprehend code written using bit shift operators in Java.

Previous Post
Next Post