Hi Bit Manipulator, today we will see some amazing logic that will blow your mind. If you see these formulas the first time then you will get confused and then, you will try to mug up.

I will breakdown all the formulas with proper examples. Before that, I am assuming you know the basic concepts of bitwise operators and how to use them. If not then first do through this post.

Let's get started.

Bit Manipulation formulas | Code Examples | Java

Before reading the next sentence please go through the below image. It will help you to imagine the concept.

Hope You find a pattern. If not Let me Explain. Take any number let's say 23. There are many ways to convert any number into binary But do you know how to do that using BitWise Operators? 

The left Shift (<<) operator is the hero operator in bitwise manipulation. A number of form 1<<k has one bit in position and all other bits are zero, so we can use such numbers to access single bits of numbers. The kth bit of a number is one exactly when x & (1 << k) is not zero.

1. Bit Representation of any number

public class BitsManipulation {
    public static void main(String[] args) {
        int x=23;
        for (int i = 15; i >= 0; i--) {
            if ((x & (1 << i)) != 0) {
                System.out.print("1");
            } else {
                System.out.print("0");
            }
        }
    }
}

Output:

0000000000010111


2. Set kth bit of a number to one

' | '  operator is very helpful here. We know 1<<k gives us every bit of a number. Now my aim is to set a bit to one if it's zero then 0 | 1 will give me 1 and if the bit is already one then 1 | 1 will give me 1.

public class SetKthBitToOne {
   public static void main(String[] args) {
        int givenNum=34;
        System.out.println("Given Number : "+givenNum);
        System.out.println(givenNum + " in bits");
        for (int i = 15; i >= 0; i--) {
            if ((givenNum & (1 << i)) != 0) {
                System.out.print("1");
            } else {
                System.out.print("0");
            }
        }
        System.out.println("\nsetting 4th bit(k=3) as 1");
        int afterBitsetNum= givenNum | (1<<3);
        System.out.println("afterBitsetNum : "+afterBitsetNum);
        System.out.println(afterBitsetNum + " in bits");
        for (int i = 15; i >= 0; i--) {
            if ((afterBitsetNum & (1 << i)) != 0) {
                System.out.print("1");
            } else {
                System.out.print("0");
            }
        }
   }
}

Output:

Given Number : 34
34 in bits
0000000000100010
setting 4th bit(k=3) as 1
afterBitsetNum : 42
42 in bits
0000000000101010


3. Set kth bit of a number to zero

Now we have to invert our concept. Which bitwise operator comes to your mind??
The NOT (~) operator. if we invert the result of 1<<k  then use & operator, our desired bit will set to zero. because only 1 & 1 will give 1.


public class SetKthBitToZero {
   public static void main(String[] args) {
	    int givenNum=56;
        System.out.println("Given Number : "+givenNum);
        System.out.println(givenNum + " in bits");
        for (int i = 15; i >= 0; i--) {
            if ((givenNum & (1 << i)) != 0) {
                System.out.print("1");
            } else {
                System.out.print("0");
            }
        }
        System.out.println("\nsetting 4th bit(k=3) as 1");
        int afterBitsetNum= givenNum & ~ (1<<3);
        System.out.println("afterBitsetNum : "+afterBitsetNum);
        System.out.println(afterBitsetNum + " in bits");
        for (int i = 15; i >= 0; i--) {
            if ((afterBitsetNum & (1 << i)) != 0) {
                System.out.print("1");
            } else {
                System.out.print("0");
            }
        }
	}
}

Output:

Given Number : 56
56 in bits
0000000000111000
setting 4th bit(k=3) as 1
afterBitsetNum : 48
48 in bits
0000000000110000


4. Invert kth bit of a number

To invert a bit we don't know if it is 0 or 1. So we have to choose the operator wisely. 
& and | will not help in this question. What about XOR(^)? 0 ^ 1 = 1 and 1 ^ 1 = 0. 

public class InvertKthBit {
   public static void main(String[] args) {
	    int givenNum=78;
        System.out.println("Given Number : "+givenNum);
        System.out.println(givenNum + " in bits");
        for (int i = 15; i >= 0; i--) {
            if ((givenNum & (1 << i)) != 0) {
                System.out.print("1");
            } else {
                System.out.print("0");
            }
        }
        System.out.println("\ninverting 4th bit(k=3) ");
        int afterManipulationNum= givenNum ^ (1<<3);
        System.out.println("afterManipulationNum : "+afterManipulationNum);
        System.out.println(afterManipulationNum + " in bits");
        for (int i = 15; i >= 0; i--) {
            if ((afterManipulationNum & (1 << i)) != 0) {
                System.out.print("1");
            } else {
                System.out.print("0");
            }
        }
	}
}

Output:

Given Number : 78
78 in bits
0000000001001110
inverting 4th bit(k=3)
afterManipulationNum : 70
70 in bits
0000000001000110


5. Set last one bit of a number to 0

According to the question, You may think of a loop to solve this. But this can be solved with a formula. If we ANDing the given Number with (givenNumber - 1) then we can set the last one bit to 0.
See the bit sequence of consecutive numbers 0000(1), 0001(1), 0010(2), 0011(3), 0100(4).

public class Setlast1to0 {
   public static void main(String[] args) {
	    int givenNum=22;
        System.out.println("Given Number : "+givenNum);
        System.out.println(givenNum + " in bits");
        for (int i = 15; i >= 0; i--) {
            if ((givenNum & (1 << i)) != 0) {
                System.out.print("1");
            } else {
                System.out.print("0");
            }
        }
        System.out.println("\nSetting last one bit of number to zero");
        int afterManipulationNum= givenNum & (givenNum-1) ;
        System.out.println("afterManipulationNum : "+afterManipulationNum);
        System.out.println(afterManipulationNum + " in bits");
        for (int i = 15; i >= 0; i--) {
            if ((afterManipulationNum & (1 << i)) != 0) {
                System.out.print("1");
            } else {
                System.out.print("0");
            }
        }
	}
}

Output:

Given Number : 22
22 in bits
0000000000010110
Setting last one bit of number to zero
afterManipulationNum : 20
20 in bits
0000000000010100


6. Sets all the one bits to zero, except the last one bit

For this question also there is a formula. If we ANDing the given number with negative of the given number. We will get our desired solution.

public class SetAll1to0ExceptLast1 {
   public static void main(String[] args) {
	    int givenNum=22;
        System.out.println("Given Number : "+givenNum);
        System.out.println(givenNum + " in bits");
        for (int i = 15; i >= 0; i--) {
            if ((givenNum & (1 << i)) != 0) {
                System.out.print("1");
            } else {
                System.out.print("0");
            }
        }
        System.out.println("\nSetting all 1 bits to 0 except last one");
        int afterManipulationNum= givenNum & - givenNum;
        System.out.println("afterManipulationNum : "+afterManipulationNum);
        System.out.println(afterManipulationNum + " in bits");
        for (int i = 15; i >= 0; i--) {
            if ((afterManipulationNum & (1 << i)) != 0) {
                System.out.print("1");
            } else {
                System.out.print("0");
            }
        }
	}
}

Output:

Given Number : 22
22 in bits
0000000000010110
Setting last one bit of number to zero
afterManipulationNum : 2
2 in bits
0000000000000010


7. Invert all the bits after the last one bit

See the 5th question if we ORing the concept, all bits will be inverted after the last one bit.

public class InvertAllBitsAfterlast1Bit {
   public static void main(String[] args) {
	    int givenNum=22;
        System.out.println("Given Number : "+givenNum);
        System.out.println(givenNum + " in bits");
        for (int i = 15; i >= 0; i--) {
            if ((givenNum & (1 << i)) != 0) {
                System.out.print("1");
            } else {
                System.out.print("0");
            }
        }
        System.out.println("\nInverting bits after the last one bit");
        int afterManipulationNum= givenNum | (givenNum - 1);
        System.out.println("afterManipulationNum : "+afterManipulationNum);
        System.out.println(afterManipulationNum + " in bits");
        for (int i = 15; i >= 0; i--) {
            if ((afterManipulationNum & (1 << i)) != 0) {
                System.out.print("1");
            } else {
                System.out.print("0");
            }
        }
	}
}

Output:

Given Number : 80
80 in bits
0000000001010000
Inverting bits after the last one bit
afterManipulationNum : 95
95 in bits
0000000001011111


Hope this tutorial helps you to understand the concept of bit manipulation.😀

Please share this tutorial with your friends!