Sitemap
Yodgorbek Komilov

Yodgorbek Komilov

Bit Manipulation in Java: A Full Guide for Beginners

5 min readJan 7, 2025

--

Bit manipulation is a technique that allows you to manipulate individual bits of data in an efficient manner. This technique is widely used in low-level programming, cryptography, algorithms, and other performance-critical applications where memory and execution speed are crucial. In Java, bit manipulation is primarily performed using bitwise operators.

1. Understanding Bitwise Operators in Java

Java provides a set of operators to perform bitwise operations. These operators work on the binary representations of integers.

  • AND (&): Performs a bitwise AND operation. The result bit is 1 if both corresponding bits are 1.
  • OR (|): Performs a bitwise OR operation. The result bit is 1 if at least one of the corresponding bits is 1.
  • XOR (^): Performs a bitwise XOR operation. The result bit is 1 if the corresponding bits are different.
  • NOT (~): Performs a bitwise NOT operation. It flips each bit (0 becomes 1, and 1 becomes 0).
  • Left Shift (<<): Shifts the bits of the number to the left by a specified number of positions. It is equivalent to multiplying the number by 2 for each shift.
  • Right Shift (>>): Shifts the bits of the number to the right by a specified number of positions. It is equivalent to dividing the number by 2 for each shift.
  • Unsigned Right Shift (>>>): Shifts the bits to the right, filling the leftmost bits with zeroes, irrespective of the sign of the number.

2. Common Bit Manipulation Techniques

Here are some commonly used bit manipulation techniques:

a) Checking if a number is odd or even

You can check whether a number is odd or even using the bitwise AND operator (&).

  • Even number: The least significant bit (LSB) is 0.
  • Odd number: The least significant bit (LSB) is 1.

Example:

public class BitManipulation {
public static void main(String[] args) {
int num = 5;
if ((num & 1) == 0) {
System.out.println(num + " is even");
} else {
System.out.println(num + " is odd");
}
}
}

b) Counting the number of set bits (1s) in a number

To count how many bits are set (1s) in a number, we can use the following technique, which involves repeatedly turning off the rightmost set bit.

Example:

public class BitManipulation {
public static void main(String[] args) {
int num = 29; // 11101 in binary
int count = 0;
while (num > 0) {
num = num & (num - 1); // Turn off the rightmost set bit
count++;
}
System.out.println("Number of set bits: " + count); // Output: 4
}
}

c) Reversing the bits of a number

Get Yodgorbek Komilov’s stories in your inbox

Join Medium for free to get updates from this writer.

You can reverse the bits of a number by iterating through each bit, shifting the bits of the number, and building the reversed result.

public class BitManipulation {
public static void main(String[] args) {
int num = 12345;
int reversed = 0;
while (num > 0) {
reversed = (reversed << 1) | (num & 1); // Shift left and add the last bit
num >>= 1; // Shift the number right
}
System.out.println("Reversed bits: " + reversed);
}
}

d) Swapping two numbers without using a temporary variable

You can swap two numbers using XOR to manipulate bits without using extra memory.

Example:

public class BitManipulation {
public static void main(String[] args) {
int a = 5;
int b = 10;

System.out.println("Before Swap: a = " + a + ", b = " + b);

a = a ^ b; // XOR a and b and store in a
b = a ^ b; // XOR a and b (which is now XOR of original a and b) to get the original a
a = a ^ b; // XOR a and b (which is now original a and b) to get the original b

System.out.println("After Swap: a = " + a + ", b = " + b);
}
}

e) Checking if a number is a power of two

A number is a power of two if it only has one bit set to 1. This can be checked by the condition (num & (num - 1)) == 0.

Example:

public class BitManipulation {
public static void main(String[] args) {
int num = 16; // 10000 in binary
if ((num & (num - 1)) == 0) {
System.out.println(num + " is a power of two");
} else {
System.out.println(num + " is not a power of two");
}
}
}

f) Finding the rightmost set bit

To find the rightmost set bit, you can use the expression num & -num.

public class BitManipulation {
public static void main(String[] args) {
int num = 12; // 1100 in binary
int rightmostSetBit = num & -num; // Finds the rightmost set bit
System.out.println("Rightmost set bit: " + rightmostSetBit); // Output: 4
}
}

g) Clearing the rightmost set bit

To clear the rightmost set bit, you can use the expression num = num & (num - 1).

public class BitManipulation {
public static void main(String[] args) {
int num = 12; // 1100 in binary
num = num & (num - 1); // Clears the rightmost set bit
System.out.println("After clearing the rightmost set bit: " + num); // Output: 8 (1000 in binary)
}
}

3. Adding Two Binary Numbers

You can add two binary numbers bit by bit, just as you would in elementary school addition, by keeping track of the carry.

public class BitManipulation {
public static String addBinary(String a, String b) {
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
StringBuilder result = new StringBuilder();

while (i >= 0 || j >= 0 || carry != 0) {
int sum = carry;

if (i >= 0) {
sum += a.charAt(i) - '0'; // Convert '0' or '1' to integer
i--;
}
if (j >= 0) {
sum += b.charAt(j) - '0'; // Convert '0' or '1' to integer
j--;
}

carry = sum / 2; // 1 if sum is 2 or more, else 0
result.append(sum % 2); // Append the current bit (0 or 1)
}

return result.reverse().toString(); // Reverse the result to get the correct order
}

public static void main(String[] args) {
String a = "1010";
String b = "1101";
System.out.println("Sum: " + addBinary(a, b)); // Output: "10111"
}
}

This method adds two binary strings by moving through each bit from right to left, adding the corresponding bits along with any carry, and then returning the sum as a binary string.

4. Advanced Bit Manipulation Techniques

a) Bit Masking

Bit masking allows you to manipulate specific bits of a number by using bitwise operations. It’s often used for tasks like setting, clearing, or toggling specific bits.

Example of setting a bit:

public class BitManipulation {
public static void main(String[] args) {
int num = 5; // 0101 in binary
int position = 1;
int mask = 1 << position; // Shift 1 to the left by 'position' times

num = num | mask; // Set the bit at the given position
System.out.println("After setting bit: " + num); // Output: 7 (0111 in binary)
}
}

5. Conclusion

Bit manipulation is a powerful technique in programming that allows you to efficiently solve problems by working directly with the bits of numbers. Java provides several bitwise operators that can be used for a wide range of tasks such as checking conditions, swapping values, and optimizing performance. Mastering bit manipulation can greatly improve the performance of your code, particularly in areas like algorithm design, cryptography, and systems programming.

--

--