Skip to main content

Bit Manipulation (Lecture 14)| bit manipulation operators

Java - Introduction to Programming

Lecture 14









Java provides several built-in operators and methods for performing bit manipulation operations on integer and long data types. These operations include bitwise AND, OR, XOR, left shift, right shift, and complement.

Here's a brief overview of the main bitwise operators in Java:

Bitwise AND (&): This operator compares each bit of two integer operands and returns a new integer with a bit set to 1 only if the corresponding bits of both operands are also 1.

Bitwise OR (|): This operator compares each bit of two integer operands and returns a new integer with a bit set to 1 if either or both of the corresponding bits of the operands are 1.

Bitwise XOR (^): This operator compares each bit of two integer operands and returns a new integer with a bit set to 1 if the corresponding bits of the operands are different.

Left shift (<<): This operator shifts the bits of an integer operand to the left by a specified number of bits, and fills the empty bits with 0s.

Right shift (>>): This operator shifts the bits of an integer operand to the right by a specified number of bits, and fills the empty bits with the sign bit (0 for positive numbers, 1 for negative numbers).

Unsigned right shift (>>>): This operator shifts the bits of an integer operand to the right by a specified number of bits, and fills the empty bits with 0s.

Bitwise complement (~): This operator flips each bit of an integer operand, so that 0s become 1s and vice versa.

In addition to these operators, Java provides several methods in the Integer and Long classes that can be used for more advanced bit manipulation operations. These include methods for counting the number of set bits (bits set to 1) in an integer or long, reversing the order of bits in an integer or long, and more.

Here's an example of using some of these operators in Java:

int a = 5; // binary representation: 00000101
int b = 3; // binary representation: 00000011

int c = a & b; // bitwise AND: 00000001 (1)
int d = a | b; // bitwise OR: 00000111 (7)
int e = a ^ b; // bitwise XOR: 00000110 (6)
int f = a << 2; // left shift: 00010100 (20)
int g = a >> 1; // right shift: 00000010 (2)
int h = ~a; // bitwise complement: 11111010 (-6)


Note that in the above example, we used decimal values for a and b for simplicity, but we could have also used binary or hexadecimal literals to represent the same values. For example, int a = 0b101; would assign the binary value 101 (decimal 5) to a.


Bit Manipulation


Get Bit

import java.util.*;

 

public class Bits {

   public static void main(String args[]) {

      int n = 5; //0101

      int pos = 3;

      int bitMask = 1<<pos;

 

      if((bitMask & n) == 0) {

          System.out.println("bit was zero");

      } else {

          System.out.println("bit was one");

      }

   }

}

 



Set Bit

import java.util.*;

 

public class Bits {

   public static void main(String args[]) {

      int n = 5; //0101

      int pos = 1;

      int bitMask = 1<<pos;

 

      int newNumber = bitMask | n;

      System.out.println(newNumber);

   }

}


Clear Bit

import java.util.*;

public class Bits {

  public static void main(String args[]) {

     int n = 5; //0101

     int pos = 2;

     int bitMask = 1<<pos;

     int newBitMask = ~(bitMask);

     int newNumber = newBitMask & n;

     System.out.println(newNumber);

  }

}

 



Update Bit


import java.util.*;

 

public class Bits {

   public static void main(String args[]) {

       Scanner sc = new Scanner(System.in);

       int oper = sc.nextInt();

       // oper=1 -> set; oper=0 -> clear

      int n = 5;

      int pos = 1;

     

      int bitMask = 1<<pos;

      if(oper == 1) {

          //set

          int newNumber = bitMask | n;

          System.out.println(newNumber);

      } else {

       //clear

       int newBitMask = ~(bitMask);

       int newNumber = newBitMask & n;

       System.out.println(newNumber);

      }

     

   }

}

 


Homework Problems

  1. Write a program to find if a number is a power of 2 or not.

  2. Write a program to toggle a bit a position = “pos” in a number “n”.

  3. Write a program to count the number of 1’s in a binary representation of the number.

  4. Write 2 functions => decimalToBinary() & binaryToDecimal() to convert a number from one number system to another. [BONUS]

 

Comments

Popular posts from this blog

Enter 3 numbers from the user & make a function to print their average in java, c++, python, java.

Enter 3 numbers from the user & make a function to print their average. To find the average of three numbers, you need to add the three numbers together and then divide the sum by three. Here's how you can write a function in C++, C, Python, and Java to take three numbers from the user and calculate their average: JAVA import java . util .*; public class Solutions {     public static void main ( String args []) {        Scanner sc = new Scanner ( System . in );        int a = sc . nextInt ();        int b = sc . nextInt ();        int c = sc . nextInt ();          int average = ( a + b + c ) / 3 ;        System . out . println ( average );    }    }   C++: // c++ #include <iostream> using namespace std ;...

2D Arrays | Java Complete Placement Course | Lecture 11

Java - Introduction to Programming Lecture 11 2D Arrays In Java It is similar to 2D matrices that we studied in 11th and 12th class. Creating a 2D Array - with new keyword int [][] marks = new int [ 3 ][ 3 ] ; Taking a matrix as an input and printing its elements. import java . util .*;   public class TwoDArrays {     public static void main ( String args []) {         Scanner sc = new Scanner ( System . in );         int rows = sc . nextInt ();         int cols = sc . nextInt ();           int [][] numbers = new int [ rows ][ cols ];           //input         //rows         for ( int i = 0 ; i < rows ; i ++) {             //columns  ...

Merge Sort | How do I learn merge sort?

       Merge Sort | For Beginners | Java Placement Course >> Merge sort is a popular sorting algorithm that utilizes a divide-and-conquer approach to sort elements in an array. The basic idea behind merge sort is to divide an unsorted array into two halves, recursively sort each half, and then merge the two sorted halves into a single sorted array. >>  Merge sort algorithm works by recursively dividing an array into two halves, sorting each half, and then merging them to obtain the sorted array. The basic steps of the merge sort algorithm are as follows: Divide the unsorted array into two halves, mid and left. Sort the left half recursively using merge sort algorithm. Sort the right half recursively using merge sort algorithm. Merge the two sorted halves to obtain the final sorted array. JAVA Implementation: // Merge sort public class MergeSort {     //time complexity=nlogn     public static void conquer ( int arr [], int ...