Back to Java
2026-01-207 min read

Binary & Bitwise Calculator (Java)

Learn Binary & Bitwise Calculator (Java) step by step with clear examples and exercises.

Why This Matters

In this full guide on Java binary and bitwise calculations, we aim to provide a deep understanding of these fundamental concepts and help you create an efficient binary and bitwise calculator in Java.

Understanding the Importance

  1. Interviews: Many programming interviews include questions about binary and bitwise operations, testing your ability to think logically and solve problems efficiently.
  2. Real-world applications: Binary and bitwise operations are used in various areas such as data compression, encryption, and computer graphics.
  3. Debugging: Knowing these concepts can help you understand and debug complex Java code that involves binary manipulation.
  4. Performance Optimization: Bitwise operations offer a more efficient way to perform certain tasks than their arithmetic counterparts, especially when dealing with large data sets or low-level programming.

Prerequisites

Before diving into the core concept, ensure you have a good understanding of the following:

  1. Basic Java syntax and control structures (if-else statements, loops)
  2. Data types (int, char, boolean, etc.)
  3. Operators (arithmetic, logical, bitwise)
  4. Variables and assignments
  5. Understanding of number systems (decimal, binary, hexadecimal)
  6. Familiarity with Java libraries such as java.util.Scanner for user input

Core Concept

Binary Representation

Every number has a binary representation, which is a base-2 number system consisting of 0s and 1s. For example:

Decimal: 10
Binary: 1010

In Java, we can convert decimal numbers to binary using the Integer.toBinaryString() method or by manually converting each digit.

Bitwise Operations

Bitwise operations manipulate individual bits (0s and 1s) in a number. The following operators are used for bitwise operations:

  • &: Bitwise AND
  • |: Bitwise OR
  • ^: Bitwise XOR
  • ~: Bitwise NOT
  • <<: Bitwise left shift
  • >>: Bitwise right shift

Shift Operations

Shift operations move the bits of a number to the left or right. For example:

Number: 1010 (10 in decimal)
Left shift 1: 1010 << 1 = 1100 (12 in decimal)
Right shift 1: 1010 >> 1 = 0101 (5 in decimal)

AND, OR, and XOR Operations

AND, OR, and XOR operations compare the corresponding bits of two numbers. For example:

Number A: 1010
Number B: 1101

AND (A & B): 1000 (4 in decimal)
OR (A | B): 1111 (15 in decimal)
XOR (A ^ B): 0111 (7 in decimal)

Worked Example

Let's create a simple Java binary and bitwise calculator. We'll implement the following functions:

  • binary(number): Converts a number to its binary representation
  • leftShift(number, shifts): Shifts the bits of a number to the left by a given number of positions
  • rightShift(number, shifts): Shifts the bits of a number to the right by a given number of positions
  • bitwiseAND(num1, num2): Performs bitwise AND on two numbers
  • bitwiseOR(num1, num2): Performs bitwise OR on two numbers
  • bitwiseXOR(num1, num2): Performs bitwise XOR on two numbers
  • countSetBits(number): Counts the number of set bits (bits equal to 1) in an integer
  • swapWithoutTemp(num1, num2): Swaps two numbers without using a temporary variable
  • isEvenOrOdd(number): Checks if a number is even or odd using bitwise operations
  • gcdUsingBitwiseAND(num1, num2): Finds the greatest common divisor (GCD) of two numbers using the bitwise AND operator

Here's the complete code for these functions:

import java.util.Scanner;

public class BinaryBitwiseCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter a number:");
int number = scanner.nextInt();
System.out.println("Binary representation of the number: " + binary(number));

System.out.println("\nLeft shift operations:");
System.out.print("Enter number of shifts: ");
int shifts = scanner.nextInt();
System.out.printf("Number left shifted by %d: %d\n", shifts, leftShift(number, shifts));

System.out.println("\nRight shift operations:");
System.out.print("Enter number of shifts: ");
shifts = scanner.nextInt();
System.out.printf("Number right shifted by %d: %d\n", shifts, rightShift(number, shifts));

System.out.println("\nBitwise operations:");
int num1 = 10;
int num2 = 5;
System.out.printf("Bitwise AND of %d and %d: %d\n", num1, num2, bitwiseAND(num1, num2));
System.out.printf("Bitwise OR of %d and %d: %d\n", num1, num2, bitwiseOR(num1, num2));
System.out.printf("Bitwise XOR of %d and %d: %d\n", num1, num2, bitwiseXOR(num1, num2));

System.out.println("\nCount set bits in a number:");
System.out.print("Enter a number: ");
int countSetBitsNumber = scanner.nextInt();
System.out.printf("Number of set bits in %d: %d\n", countSetBitsNumber, countSetBits(countSetBitsNumber));

System.out.println("\nSwap two numbers without using a temporary variable:");
int num3 = 7;
int num4 = 15;
swapWithoutTemp(num3, num4);
System.out.printf("Numbers swapped: %d and %d\n", num3, num4);

System.out.println("\nCheck if a number is even or odd using bitwise operations:");
int checkEvenNumber = 10;
System.out.printf("Is %d even? %s\n", checkEvenNumber, isEvenOrOdd(checkEvenNumber));

System.out.println("\nFind the greatest common divisor (GCD) using bitwise AND operator:");
int num5 = 36;
int num6 = 24;
System.out.printf("GCD of %d and %d: %d\n", num5, num6, gcdUsingBitwiseAND(num5, num6));
}

public static String binary(int number) {
return Integer.toBinaryString(number);
}

public static int leftShift(int number, int shifts) {
return number << shifts;
}

public static int rightShift(int number, int shifts) {
return number >> shifts;
}

public static int bitwiseAND(int num1, int num2) {
return num1 & num2;
}

public static int bitwiseOR(int num1, int num2) {
return num1 | num2;
}

public static int bitwiseXOR(int num1, int num2) {
return num1 ^ num2;
}

public static void swapWithoutTemp(int num1, int num2) {
num1 = num1 ^ num2;
num2 = num1 ^ num2;
num1 = num1 ^ num2;
}

public static String isEvenOrOdd(int number) {
if ((number & 1) == 0) {
return "even";
} else {
return "odd";
}
}

public static int countSetBits(int number) {
int count = 0;
for (int i = 0; i < 32; i++) {
if ((number & (1 << i)) != 0) {
count++;
}
}
return count;
}

public static int gcdUsingBitwiseAND(int num1, int num2) {
while (num2 != 0) {
int temp = num1 % num2;
num1 = num2;
num2 = temp;
}
return num1;
}
}

Common Mistakes

  1. Forgetting the &, |, or ^ operator: Make sure to use the correct bitwise operator for the desired operation.
  2. Misunderstanding shift operations: Remember that left shifts fill vacated bits with zeros, while right shifts fill them with signs (for signed integers).
  3. Incorrect handling of negative numbers: Be aware that the behavior of shift operations on negative numbers depends on the platform and the compiler used.
  4. Ignoring the order of operations: Remember that bitwise operators have higher precedence than arithmetic operators, so you may need to use parentheses for clarity.
  5. Not considering edge cases: Ensure your functions handle edge cases such as zero or negative numbers appropriately.

Practice Questions

  1. Write a function to find the number of set bits (bits equal to 1) in an integer using Java recursively.
  2. Implement a function to swap two numbers without using a temporary variable iteratively.
  3. Write a function to check if a number is a power of two using bitwise operations.
  4. Given two integers, write a function to find their least common multiple (LCM) using the bitwise OR operator and the GCD.
  5. Implement a function to perform modulo exponentiation (a^b mod c) using bitwise operations.
  6. Write a function to convert an integer to its hexadecimal representation using Java.
  7. Create a function that takes a binary string as input and returns the decimal equivalent of the binary number.
  8. Implement a function to find the parity (even or odd) of a non-negative integer using bitwise operations and without recursion.
  9. Write a function to count the number of 1s in the binary representation of an unsigned 32-bit integer.
  10. Create a function that checks if two integers are relatively prime (their greatest common divisor is 1).

FAQ

  1. Why do we need to understand binary and bitwise operations?
  • They are essential for understanding computer hardware and low-level programming.
  • They help optimize code by manipulating individual bits directly.
  • They are commonly asked in programming interviews.
  • Understanding these concepts can lead to a deeper understanding of algorithms and data structures.
  1. What is the difference between left shift (<<) and right shift (>>)?
  • Left shift moves bits to the left, filling vacated bits with zeros.
  • Right shift moves bits to the right, filling vacated bits with signs for signed integers or zeros for unsigned integers.
  1. What is the difference between AND (&), OR (|), and XOR (^) operations?
  • AND returns 1 only if both bits are 1; otherwise, it returns 0.
  • OR returns 1 if either bit is 1; otherwise, it returns 0.
  • XOR returns 1 if the number of set bits in the corresponding positions of the two numbers is odd; otherwise, it returns 0.
  1. Why are bitwise operators faster than their arithmetic counterparts?
  • Bitwise operations operate on individual bits directly, which can be more efficient for certain tasks, especially when dealing with large data sets or low-level programming.
  1. Can we perform modulo exponentiation using bitwise operations? If so, why is it beneficial?
  • Yes, modulo exponentiation can be performed using bitwise operations by reducing the exponent to a power of 2 and performing repeated squaring with multiplication by the base and shifting right for each bit set in the exponent. This method is more efficient than traditional methods when the exponent is large because it avoids costly divisions and reduces the number of multiplications required.
  1. Can we convert an integer to its hexadecimal representation using Java?
  • Yes, you can convert an integer to its hexadecimal representation in Java by using the Integer.toHexString() method or by manually converting each digit.
  1. How do we check if a number is a power of two using bitwise operations?
  • You can check if a number is a power of two using bitwise operations by checking if the number and (number - 1)
Binary &amp; Bitwise Calculator (Java) | Java | XQA Learn