Bitwise Operators in Java

Introduction to bitwise operators in Java

Bitwise operators are a set of operators that perform operations on individual bits of a number. They can be used with any integral type in Java (char, short, int, long, byte). Bitwise operators are often used in low-level programming, but they can also be useful in other applications, such as cryptography, error detection, and compression.

The following table shows the list of bitwise operators in Java:
Operator Description
`&` Bitwise AND: Performs a logical AND operation on each corresponding bit of the two operands. The result is 1 if both bits are 1, and 0 otherwise.
`|` Bitwise OR: Performs a logical OR operation on each corresponding bit of the two operands. The result is 1 if either bit is 1, and 0 otherwise.
`^` Bitwise XOR: Performs a logical XOR operation on each corresponding bit of the two operands. The result is 1 if only one bit is 1, and 0 otherwise.
`~` Bitwise complement: Inverts each bit of the operand.
`<<` Left shift: Shifts the bits of the operand to the left by the specified number of positions. The rightmost bits are discarded, and the leftmost bits are filled with zeros.
`>>` Right shift: Shifts the bits of the operand to the right by the specified number of positions. The leftmost bits are discarded, and the rightmost bits are filled with zeros (for signed right shift) or ones (for unsigned right shift).
Bitwise operators can be used to perform a variety of tasks, such as:
  • Checking whether a bit is set or not
  • Setting or clearing a bit
  • Toggling a bit
  • Performing bit-level arithmetic operations
  • Performing bit-level masking operations
  • Implementing bit-level data structures

Exercises

Get input from the user and the number of bits to shift. Left shift the number by the number of bits to get the encrypted text. Get the encrypted text and right shift the text by the same number of bits to get the plain text


import java.util.Scanner;
public class javalabclass{
    public static void main(String args[]) 
    {
      
      //an user can take a number as input and then left shift it by as many bits 
      //he wishes and we can call that to be encrypted text
      //we can take the encrypted text and right shift by the same number of bits 
      //to get the plain text 
      System.out.println("Enter the plain text ");
      Scanner obj = new Scanner(System.in);
        int plaintext = obj.nextInt();
        System.out.println("Enter the number of bits for left shifting");
        int key = obj.nextInt();
        System.out.println(plaintext<<2);
        System.out.println("Enter the encrypted text");
        int encryptedtext = obj.nextInt();
        System.out.println(encryptedtext >> 2);
      
    }
}

Output
Enter the plain text 
4
Enter the number of bits for left shifting
2
16
Enter the encrypted text
16
4