Bit Operations in JAVA

Java supports multiple bit operations like :

  • OR ( | )
  • AND ( & )
  • XOR ( ^ )
  • Left Shift ( << )
  • Right Shift ( >> )
  • Unsigned Right Shift ( >>> )
  • Complement ( ! )

Bitwise OR ( | )

OR operation follows the following truth table:

ABA | B
000
011
101
111

So for example we have two integers A = 8 and B = 7

OperationBinaryDecimal
010008
001117
OR0111115

After OR operation, result will be  0 1 1 1 1 which is 15


Bitwise AND ( & )

AND operation follows the following truth table.

ABA & B
000
010
100
111

So, in the same example shared above , let us consider two integers A = 8 and B = 7

OperationBinaryDecimal
010008
001117
AND000000

After AND operation , result will be 0 0 0 0 0

Bitwise XOR ( ^ )

XOR (Exclusive OR) operation follows the following truth table.

ABA ^ B
000
011
101
110

As shown above, the output is only one when either of the two inputs are one. If both or none are one , then output is zero.

In this case, lets change the example a bit to consider the scenario when both the bits are one. Let us consider two integers A = 8 and B = 15

OperationBinaryDecimal
010008
0111115
XOR001117

After AND operation , result will be 0 0 1 1 1 which is 7 in decimal.

Left Shift ( << )

Left shift operation allows you to shift bits to the left

This is arithmetic shift left which will take care of the signed bit. Lets consider the below examples where first we will left shift  4 bit  (positive and negative number)

Example 1: (Positive Decimal)

Example 2: (Negative Decimal)

As you can see in above examples, signed but is preserved and all bits have shifted left.

Right Shift ( >> )

Right shift operation allows you to shift bits to the right

This is arithmetic shift right which will again take care of the signed bit as in the left bit shift shown above. Below examples will give further understanding about the same.

Example 1: (Positive Decimal)

Example 2: (Negative Decimal)

As expected, bits are shifted right keeping the signed bit preserved.

Unsigned right Shift ( >> )

Unsigned right shift operation allows you to shift bits to the right

This is logical shift right which will not take care of the signed bit. Lets understand it through the same example as of arithmetic shift right.

Example 1: (Positive Decimal)

Example 2: (Negative Decimal)

As clear from above, difference in arithmetic and logic shift right only differs when input is negative.  In this case, signed bit is not preserved and hence the output is different.

Compliment ( ~ )

Compliment operation follows the following truth table.

A~ A
01
10

As shown above, it will just flip all Ones to Zeros and all Zeros to Ones

In this case, lets take compliment of decimal number 3

OperationBinaryDecimal
000113
Compliment1110028

After compliment operation , result will be 1 1 1 0 0 which is 28 in decimal.

Leave a Reply

Your email address will not be published. Required fields are marked *