The process of modifying individual bits or groups of bits within a binary representation of data is known as bit manipulation. It is often used in computer programming to execute bit-level operations on data, which can be more efficient than typical arithmetic or logic operations.
Bit manipulation is often used for a variety of reasons, including:
Following are the types of bitwise operators:
| & | bitwise AND |
| | | bitwise OR |
| ^ | bitwise XOR |
| ~ | bitwise complement or NOT |
| << | left shift |
| >> | signed right shift |
| >>> | unsigned right shift |
| A | B | A & B | A | B | A ^ B | ~A |
|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | 1 |
| 0 | 1 | 0 | 1 | 1 | 1 |
| 1 | 0 | 0 | 1 | 1 | 0 |
| 1 | 1 | 1 | 1 | 0 | 0 |
| A | B | A<<B | A>>B | A>>>B |
| 25 | 2 | 100 | 6 | 6 |
| -25 | 2 | -100 | -7 | 1073741817 |
Some common uses of bit manipulation include:
int num = 11;
if ((num & 1) == 0)
{
System.out.println("Even");
}
else
{
System.out.println("Odd");
} int num = 5;
int mask = 1 << 2; // set the third bit to 1
num |= mask;
System.out.println(num); // prints 5 + 4 = 9 int num = 13;
int mask = ~(1 << 3); // clear the fourth bit
num &= mask;
System.out.println(num); // prints 13 - 8 = 5 int num = 10;
int mask = 1 << 1; // flip the second bit
num ^= mask;
System.out.println(num); // prints 10 - 2 = 8 Bit manipulation can also be used in various algorithms and data structures such as:
java.util.BitSet class provides a convenient way to work with bitsets.Let us discuss the problems related to bit manipulation in the next topic.
Note: also read about DSA: Sliding Window Technique
Please follow me to read my latest post on programming and technology if you like my post.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
A design pattern is a reusable solution to a commonly occurring problem in software design. They…
Factory Method is a creational design pattern that deals with the object creation. It separates…
You are given two singly linked lists that intersect at some node. Your task is…
A builder plans to construct N houses in a row, where each house can be…
Find the length of the longest absolute path to a file within the abstracted file…
You manage an e-commerce website and need to keep track of the last N order…