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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…