Core Java

Java Flip Bits Number Example

Bit manipulation is an important concept in Java programming, especially when dealing with low-level operations, optimization, cryptography, networking, and competitive programming. One of the most common bit manipulation tasks is flipping the bits of a number. In this article, we will understand how bit flipping works in Java, explore different approaches, and learn how to flip all bits or only significant bits with detailed examples.

1. Overview

Flipping bits means changing every binary digit in a number to its opposite value. In binary representation, a number is stored using only two digits: 0 and 1. During the flipping process: 1 becomes 0 and vice versa. This operation is also known as bit inversion or bit complement. For example, consider the decimal number 5. Its 8-bit binary representation is: 00000101. If we flip every bit:

Original Binary: 00000101
Flipped Binary: 11111010

Here, the first six 0s are converted into 1s, the second last 1 is changed to 0, and the last 0 is changed to 1. The following table shows the transformation clearly:

DecimalBinaryFlipped Binary
50000010111111010

Bit flipping is commonly used in bit masking operations, low-level system programming, data encryption and security algorithms, image processing, performance optimization, and competitive programming problems.

Java provides built-in Bitwise Operators that make bit manipulation operations simple and highly efficient. The most commonly used operator for flipping bits is the Bitwise NOT (~) operator, which inverts every bit in a number. Since bitwise operations work directly on binary data at the hardware level, they are extremely fast compared to many arithmetic operations.

1.1 Understanding Bit Flipping

Computers store numbers internally in binary format using bits. A bit can have only two values: 0 and 1. Each bit represents a power of 2. For example, the decimal number 10 is stored in binary as:

Decimal Number: 10
Binary Number : 00001010

Flipping bits means converting 1 to 0 and 0 to 1. after flipping all bits:

Original : 00001010
Flipped  : 11110101

Bit flipping is commonly used in low-level programming, bit masking operations, cryptography and encoding, performance optimization, and hardware-level computations.

Java stores integers using a 32-bit signed representation called two’s complement. Because of this internal representation, flipping all bits of a positive number generally produces a negative number. For example:

Number  : 10
Binary  : 00000000 00000000 00000000 00001010

After ~ :
Binary  : 11111111 11111111 11111111 11110101
Result  : -11

1.2 Using the Bitwise NOT Operator

Java provides the bitwise NOT operator ~, which is used to flip all bits of a number. It is one of the most fundamental bitwise operators and works directly at the binary level. The syntax is: ~number. From a theoretical perspective, the bitwise NOT operator performs a unary operation, meaning it operates on a single operand and inverts every bit in its binary representation. This includes both the magnitude and sign bit in signed number representations, which is why the result often appears as a negative number in Java.

The operator works on each bit individually:

Original BitFlipped Bit
01
10

In Java, integers are stored using 32-bit signed two’s complement representation. This means the most significant bit represents the sign (0 for positive, 1 for negative), and the remaining bits represent the value. When the ~ operator is applied, all 32 bits are inverted, including the sign bit, which results in a new two’s complement value.

1.3 Flipping Only the Significant Bits

Sometimes we do not want to flip all 32 bits of an integer, especially in Java where integers are stored in 32-bit two’s complement format. Instead, we may only want to flip the meaningful or significant bits that actually represent the number. This approach is commonly used in competitive programming and bit manipulation problems to avoid unintended effects from leading sign bits. For example:

Number = 10
Binary = 1010

Here, we consider only the significant part of the binary representation (i.e., ignoring leading zeros beyond the meaningful bit-length). Flipping only these bits gives: 1010 → 0101. To achieve this in practice, we cannot directly use the ~ operator, because it flips all 32 bits. Instead, we isolate the significant bits using a bitmask.

A bitmask is a binary number that helps us control which bits should be affected during an operation. In this case, we create a mask that contains all 1s up to the most significant bit of the number. The general steps are:

  • Determine the number of significant bits in the number
  • Create a bitmask with all 1s for those bits (e.g., for 4 bits → 1111)
  • Use XOR (^) between the number and the mask to flip only those bits

The XOR operator is useful here because it flips a bit only when the corresponding mask bit is 1, and keeps it unchanged when the mask bit is 0.

This technique ensures that only the effective portion of the binary representation is inverted, making it highly useful in problems involving binary transformations, custom encoding schemes, and optimized bit-level computations.

1.4 Alternative Methods

Apart from the Bitwise NOT (~) operator, Java also provides other techniques for flipping bits efficiently. Common approaches include using the XOR (^) operator with a bit mask and manually processing bits using loops and bitwise operations. XOR-based flipping is useful when you want controlled bit inversion using a mask instead of flipping the entire 32-bit representation, while manual bit manipulation helps developers understand how binary operations work internally at the bit level. These approaches are commonly used in competitive programming, low-level system programming, and optimization-related problems.

2. Code Example

The following example demonstrates different techniques for flipping bits in Java. The program shows how to flip all bits using the Bitwise NOT operator, flip only significant bits using masks and XOR, and manually perform bit flipping using loops and bitwise operations.

// FlipBitsDemo.java

public class FlipBitsDemo {

    public static void main(String[] args) {

        int number = 10;

        System.out.println("Original Number : " + number);
        System.out.println("Original Binary : "
                + Integer.toBinaryString(number));

        System.out.println("----------------------------------");

        /*
         * 1. Flip All Bits Using Bitwise NOT Operator
         */
        int flippedAll = ~number;

        System.out.println("1. Using Bitwise NOT (~)");
        System.out.println("Flipped Number : " + flippedAll);
        System.out.println("Flipped Binary : "
                + Integer.toBinaryString(flippedAll));

        System.out.println("----------------------------------");

        /*
         * 2. Flip Only Significant Bits
         */
        int bitLength = Integer.toBinaryString(number).length();

        int mask = (1 << bitLength) - 1;

        int significantFlip = number ^ mask;

        System.out.println("2. Flipping Only Significant Bits");
        System.out.println("Bit Length     : " + bitLength);
        System.out.println("Mask            : " + mask);
        System.out.println("Mask Binary     : "
                + Integer.toBinaryString(mask));

        System.out.println("Flipped Number  : " + significantFlip);
        System.out.println("Flipped Binary  : "
                + Integer.toBinaryString(significantFlip));

        System.out.println("----------------------------------");

        /*
         * 3. Using XOR Directly
         */
        int xorMask = 15;

        int xorResult = number ^ xorMask;

        System.out.println("3. Using XOR Operator");
        System.out.println("XOR Mask        : " + xorMask);
        System.out.println("Mask Binary     : "
                + Integer.toBinaryString(xorMask));

        System.out.println("XOR Result      : " + xorResult);
        System.out.println("Result Binary   : "
                + Integer.toBinaryString(xorResult));

        System.out.println("----------------------------------");

        /*
         * 4. Manual Bit Flipping Using Loop
         */
        int temp = number;

        int manualResult = 0;

        int position = 0;

        while (temp > 0) {

            int bit = temp & 1;

            if (bit == 0) {

                manualResult |= (1 << position);
            }

            temp >>= 1;

            position++;
        }

        System.out.println("4. Manual Bit Flipping");
        System.out.println("Manual Result   : " + manualResult);
        System.out.println("Manual Binary   : "
                + Integer.toBinaryString(manualResult));
    }
}

2.1 Code Example

The FlipBitsDemo program demonstrates multiple techniques for flipping bits in Java using bitwise operations and manual logic. First, the program initializes an integer variable named number with the value 10 and prints both its decimal and binary representations using Integer.toBinaryString(). The first approach uses the Bitwise NOT (~) operator, which flips all 32 bits of the integer and stores the result in flippedAll. Since Java integers use two’s complement representation, flipping all bits of a positive number usually results in a negative value. The second approach flips only the significant bits of the number by first calculating the binary length using Integer.toBinaryString(number).length(), then creating a bit mask using the expression (1 << bitLength) – 1. This mask contains all 1s equal to the number of meaningful bits, and the XOR operator (^) is used to flip only those bits, storing the result in significantFlip. The third approach demonstrates direct XOR-based flipping using a predefined mask value of 15 (binary 1111), which selectively flips the lower four bits of the number and stores the result in xorResult. Finally, the program performs manual bit flipping using a loop. A temporary variable named temp is used to traverse the binary representation bit by bit. The expression temp & 1 extracts the last bit, and if the extracted bit is 0, the corresponding bit position in manualResult is set using the OR operator (|) and left shift operator (<>= 1 and the position counter is incremented. At the end of execution, the program prints the results and binary representations for all approaches, providing a complete demonstration of different bit-flipping techniques in Java.

2.2 Code Output

Original Number : 10
Original Binary : 1010

----------------------------------

1. Using Bitwise NOT (~)
Flipped Number : -11
Flipped Binary : 11111111111111111111111111110101

----------------------------------

2. Flipping Only Significant Bits
Bit Length     : 4
Mask            : 15
Mask Binary     : 1111
Flipped Number  : 5
Flipped Binary  : 101

----------------------------------

3. Using XOR Operator
XOR Mask        : 15
Mask Binary     : 1111
XOR Result      : 5
Result Binary   : 101

----------------------------------

4. Manual Bit Flipping
Manual Result   : 5
Manual Binary   : 101

The output demonstrates how different bit-flipping techniques behave in Java and how the result changes depending on whether all bits or only the significant bits are flipped. Initially, the program prints the original number 10 and its binary representation 1010. In the first approach, the Bitwise NOT operator (~) flips all 32 bits of the integer. The binary value 00000000 00000000 00000000 00001010 becomes 11111111 11111111 11111111 11110101, which represents -11 in Java, because integers are stored using two’s complement representation. This follows the formula ~n = -(n + 1). In the second approach, only the significant bits are flipped. Since the binary representation of 10 contains 4 meaningful bits, the program creates a mask 1111 (decimal 15) and performs an XOR operation. The calculation 1010 ^ 1111 produces 0101, which equals 5. The third approach also uses XOR directly with the mask value 15, producing the same result because XOR with 1 flips a bit while XOR with 0 keeps the bit unchanged. Finally, the manual bit-flipping approach processes each bit individually using a loop. The expression temp & 1 extracts the last bit, and whenever the extracted bit is 0, the corresponding bit in the result is set using the OR operator and left shift operation. The number is continuously shifted right until all bits are processed. This manual method also produces the flipped binary value 0101, which equals 5. Overall, the output clearly illustrates the difference between flipping all 32 bits using the Bitwise NOT operator and flipping only the meaningful bits using masks, XOR operations, or manual bit processing.

3. Conclusion

Bit flipping is one of the most fundamental and widely used operations in bit manipulation. In Java, bit flipping can be performed efficiently using the Bitwise NOT (~) operator, XOR operations, masks, or manual bit-processing techniques. The Bitwise NOT operator flips all 32 bits of an integer, which often produces negative values because Java uses two’s complement representation for signed numbers. In situations where only the meaningful bits should be inverted, bit masks and XOR operations provide a more controlled and practical approach. Manual bit flipping further helps developers understand how binary operations work internally at the bit level. Understanding these techniques is extremely useful in areas such as low-level programming, optimization, networking, cryptography, image processing, and competitive programming. By mastering bit manipulation concepts like bit flipping, developers can write more efficient, optimized, and performance-oriented Java applications.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button