Program in C to Toggle Bits of an Integer

Program in C to Toggle Bits of an Integer

Toggling a bit means changing its state: a 0 becomes 1, and a 1 becomes 0. This operation is widely used in low-level programming, embedded systems, and digital logic applications. In this article, we will learn how to toggle all bits of an integer using C programming.

Understanding The Problem

An integer in C is stored in binary form. For example, 5 is 101 in binary. Toggling all bits of 5 would give 010 (for 3-bit representation) or ~5 in full 32-bit representation. The problem requires taking an integer as input and toggling all its bits to get the complement.

Program 1: Using Bitwise NOT Operator (~)

The simplest way to toggle all bits of an integer is to use the bitwise NOT operator (~). This operator inverts every bit in the number.

#include <stdio.h>

int main() {

    int n;

    printf("Enter an integer: ");
    scanf("%d", &n);

    int toggled = ~n;

    printf("Original number: %d\n", n);
    printf("Toggled number: %d\n", toggled);

    return 0;

}

This program uses the ~ operator to invert all bits of the given integer. The result is printed as a decimal value, which represents the two’s complement of the original number.

Program 2: Toggling Specific Bit Positions

Sometimes, we want to toggle only a specific bit instead of all bits. This can be done using the XOR (^) operator with a mask representing the bit position.

#include <stdio.h>

int main() {

    int n, pos;

    printf("Enter an integer: ");
    scanf("%d", &n);

    printf("Enter bit position to toggle (0 for LSB): ");
    scanf("%d", &pos);

    int toggled = n ^ (1 << pos);

    printf("Original number: %d\n", n);
    printf("Toggled number: %d\n", toggled);

    return 0;

}

In this program, a mask is created by left-shifting 1 by the bit position. XORing the mask with the number toggles only the selected bit while leaving other bits unchanged.

FAQs

Q1: What is the difference between toggling all bits and a single bit?
Toggling all bits changes the entire binary representation, while toggling a single bit changes only that position.

Q2: How can I find the binary representation of the toggled number?
You can use a loop to print each bit using (number >> i) & 1 for the required number of bits.

Q3: Is the result always positive?
No. Toggling all bits with ~ may produce negative numbers due to two’s complement representation in C.

Conclusion

Toggling bits is a fundamental operation in C programming, useful for manipulating individual bits or entire numbers. Using the bitwise NOT operator and XOR, we can efficiently toggle all bits or specific bit positions. Understanding these operations helps in low-level programming and bit manipulation tasks.

References & Additional Resources

Scroll to Top