Sometimes we need to change the value of variable by performing a low level operation.In a computer system every number is stored as binary number made of 1s and 0s.The Bitwise Shift operator can change the value of a stored variable by changing its binary value.
This is a simple program to demonstrate the use of Bitwise Shift operator and learn the basics of Java Programming. We are using JDK 8u111 with Netbean IDE 8.2 to compile and run this program.
This program changes the value of a variable by changing bit values. To perform a bitwise shift we are using two byte data type variable.
Byte is one of the eight primitive data type in Java. The byte type is 8-bit signed integer data type. It means that it store integer values -128 to 127, because whenever a signed binary is used then one bit is used as a sign bit. If the signed bit is not used then the integer values are between 0 to 255.
The bit shift operator shifts certain number of bit to right or left depending on which operator you are using – right bit shift operator (>>) or left bit shift operator (<<).
The program changes the value of variable a by shifting the bit values to left.
public static void main(String args)
l = a<<2;
b = (byte)(a << 2);
System.out.println("Original value of a:" + a);
System.out.println("l and b:" + l +" "+ b);
Output – Bitwise Shift Operator
The output of the above example is given below.
Original value of a: 64
l and b: 256 0
The original value a = 64 is 0100 0000 in binary. The bit shift operator move the first 1s to 2 bit left. The new binary value is 0000 0000 which is 0.
Now the l is not limited to 8-bit like a, it is of 32 or 16 bits. The left bit shift by 2 place will be following.
l = 0000 0001 0000 0000 = 2^9 = 256