Operators Assignment 15 — Toggle a Particular Bit Using Bitwise XOR
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Toggle a Particular Bit in a Number Using Bitwise XOR

📑 On this page:
  • What does toggling a bit mean?
  • Method 1 — XOR with left shift
  • Method 2 — XOR with unsigned mask
  • Complete C Programs
  • Program Output
  • Step-by-Step Explanation
  • Warnings and caveats
  • Frequently Asked Questions
📚 In this program, you will learn:
  • What it means to toggle a bit
  • How to use the bitwise XOR operator ^
  • How to create a bit mask using the left-shift operator <<
  • How to toggle the nth bit of a number
  • How to validate a bit position before shifting

What does toggling a bit mean?

Toggling a bit means changing its current state to the opposite state. If the selected bit is 0, it becomes 1; if it is 1, it becomes 0.

newNumber = num ^ (1 << n);

The expression 1 << n creates a mask with a 1 only at bit position n. XORing that mask with the number changes only that selected bit and leaves every other bit unchanged.

  • XOR with left shift: num ^ (1 << n)
  • Unsigned mask version: num ^ (1u << n)
💡 In one line: XOR returns 1 when the two input bits differ, so XORing a bit with 1 flips it, while XORing it with 0 leaves it unchanged.
C program to toggle a particular bit in a number using bitwise XOR and left shift.

Method 1 — XOR with left shift

To toggle the nth bit, first create a mask by shifting 1 to the left n times. Then apply bitwise XOR between the original number and that mask.

Trace with num = 22 and n = 1:

Step Operation Decimal Binary Note
0 Initial number 22 00010110 Bit 1 is currently 1
1 1 << 1 2 00000010 Mask with only bit 1 set
2 22 ^ 2 20 00010100 Bit 1 changes from 1 to 0

After toggling bit 1, the number changes from 22 to 20.

Method 2 — XOR with unsigned mask

Using an unsigned literal such as 1u makes the intent clearer and avoids unnecessary signed-integer concerns when creating the mask.

newNumber = num ^ (1u << n);

This method works in exactly the same way as Method 1. The only difference is that 1u is an unsigned integer literal, which is often preferred for bitwise operations.

For example, if num = 22 and n = 1, then 1u << 1 is 2, and 22 ^ 2 is 20.

Complete C Programs

Program 1 — toggle the nth bit using XOR:

Program 1: Toggle nth bit using bitwise XOR

#include <stdio.h>

int main(void) {
    int num, n, newNumber;

    printf("Enter any number: ");
    scanf("%d", &num);

    printf("Enter the bit position to toggle (0-31): ");
    scanf("%d", &n);

    newNumber = num ^ (1 << n);

    printf("Number before toggling bit %d: %d\n", n, num);
    printf("Number after toggling bit %d: %d\n", n, newNumber);

    return 0;
}
                                

Program 2 — toggle the nth bit using an unsigned mask:

Program 2: Toggle nth bit using unsigned mask

#include <stdio.h>

int main(void) {
    int num, n, newNumber;

    printf("Enter any number: ");
    scanf("%d", &num);

    printf("Enter the bit position to toggle (0-31): ");
    scanf("%d", &n);

    newNumber = num ^ (int)(1u << n);

    printf("Number before toggling bit %d: %d\n", n, num);
    printf("Number after toggling bit %d: %d\n", n, newNumber);

    return 0;
}
                                

Both programs toggle only the requested bit. The unsigned-mask version is generally preferred for bitwise operations because it makes the unsigned nature of the mask explicit.

Program Output

Running either program with 22 and bit position 1:

Enter any number: 22
Enter the bit position to toggle (0-31): 1
Number before toggling bit 1: 22
Number after toggling bit 1: 20
                            

Since bit 1 of 22 is already set, XOR changes it to 0, producing 20.

Running either program with 20 and bit position 1:

Enter any number: 20
Enter the bit position to toggle (0-31): 1
Number before toggling bit 1: 20
Number after toggling bit 1: 22
                            

Since bit 1 of 20 is currently 0, XOR changes it to 1, producing 22.

Running either program with 10 and bit position 0:

Enter any number: 10
Enter the bit position to toggle (0-31): 0
Number before toggling bit 0: 10
Number after toggling bit 0: 11
                            

Bit 0 is the least significant bit. Since it is 0 in 10, XOR changes it to 1, producing 11.

Step-by-Step Explanation

1. Reading inputs: scanf("%d", &num) reads the number, and scanf("%d", &n) reads the bit position to toggle. The & operator passes the address of each variable.

2. Why left shift creates a mask: 1 << n moves the single 1 bit into position n. For example, 1 << 3 becomes binary 00001000.

3. Why XOR toggles the bit: XOR returns 1 when the input bits differ and 0 when they are the same. Therefore, 0 ^ 1 = 1 and 1 ^ 1 = 0, which is exactly the behavior needed to toggle a bit.

4. Why other bits remain unchanged: Every unselected bit is XORed with 0. Since 0 ^ 0 = 0 and 1 ^ 0 = 1, those bits retain their original values.

5. Why validation matters: For a 32-bit int, valid bit positions are normally 0 through 31. Shifting by a value equal to or greater than the width of the type is undefined behavior in C.

⚠️ Caution: Always validate the bit position before using it in a shift expression. For a 32-bit int, ensure that n is between 0 and 31; otherwise, the shift is undefined behavior.

Warnings and caveats

Before using bitwise operations, understand their limitations:

  • Invalid bit position. A shift count greater than or equal to the width of the type is undefined behavior. For a 32-bit int, valid positions are 0 through 31.
  • Signed integers. Toggling the sign bit of a signed integer can produce a negative value or undefined behavior, depending on the representation and operation.
  • Unsigned preferred. For bit manipulation, unsigned int is usually safer and clearer because its behavior is fully defined for bitwise operations.
  • Input validation. If the user enters invalid input, scanf() may not store a valid value. Check its return value in production code.
  • Readability. Bitwise expressions are concise, but adding comments and using meaningful variable names makes them easier to maintain.

For learning and low-level programming, XOR-based bit toggling is useful. For application code, validate inputs and prefer unsigned types for bit masks.

Frequently Asked Questions

1. Which operator is used to toggle a bit?

The bitwise XOR operator ^ is used to toggle a bit. XORing a bit with 1 flips it, while XORing it with 0 leaves it unchanged.

2. What does 1 << n mean?

It creates a mask with a single 1 at bit position n. For example, 1 << 2 is binary 00000100.

3. What is the formula to toggle the nth bit?

The formula is newNumber = num ^ (1 << n);. It changes only the nth bit and preserves all other bits.

4. Can toggling the same bit twice restore the original number?

Yes. XOR is its own inverse: (num ^ mask) ^ mask returns the original num.

5. What is the valid bit-position range for a 32-bit int?

For a 32-bit int, the valid positions are 0 through 31. Bit 0 is the least significant bit, and bit 31 is the most significant bit.

💡 Tip: After toggling a bit, print the result in binary using a loop or use a debugger to see exactly which bit changed. Then toggle the same bit again to confirm that the original number is restored.

📖 Related Tutorials

  • Previous: Check if a Number Is Negative Without Using 'if'
  • Bitwise XOR on Two Numbers Using '^'
  • Bitwise Left Shift Using '<<'
  • Bitwise AND on Two Numbers Using '&'
  • Bitwise Operators in C — Full Tutorial
  • All 15 Operator Assignments in C
  • Operators FAQ

Previous Topic: -->> 14. Check if a Number Is Negative Without Using 'if'   ||   Next Topic: -->> All Operator Assignments in C


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope, Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Accessing Structure Members
    • Structure Initialization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • Accessing Pointers — Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Using Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • Count Words, Lines in a File
    • Copy Files
    • Update File
    • Count Vowels in a File
  • Preprocessor
    • Macro Substitution Division
    • File Inclusion
    • Conditional Compilation
    • Other Directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage Classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage Classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage Classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.