C Program To Toggle NTH Bit of Number - HTML
C Program To Toggle NTH Bit of Number - HTML
Home
Programming Basics
C Programming Tutorial
C Exercises
Basic C Exercises
Bitwise Operator Exercises
Conditional Operator Exercises
If else Exercises
Switch case Exercises
Loop Exercises
Star Patterns
Number Patterns
Functions Exercises
Array Exercises
String Exercises
Pointer Exercises
File handling Exercises
Data Structures
Articles
Write for Us
Write a C program to input any number from user and toggle or invert or
flip nth bit of the given number using bitwise operator. How to toggle n th
bit of a given number using bitwise operator in C programming. C
program set nth bit of a given number if it is unset otherwise unset if it is
set.
Example
Input
Input number: 22
Input nth bit to toggle: 1
Output
Required knowledge
Bitwise operators, Data types, Variables and Expressions, Basic
input/output
Logic to toggle nth bit of a number
Toggling bit means setting a bit in its complement state. Means if bit is
currently set then change it to unset and vice versa.
To toggle a bit we will use bitwise XOR ^ operator. Bitwise XOR operator
evaluates to 1 if corresponding bit of both operands are different
otherwise evaluates to 0. We will use this ability of bitwise XOR operator
to toggle a bit. For example - if Least Significant Bit of num is 1, then num ^
1 will make LSB of num to 0. And if LSB of num is 0, then num ^ 1 will
toggle LSB to 1.
1. Input number and nth bit position to toggle from user. Store it in
some variable say num and n.
2. Left shift 1 to n times, i.e. 1 << n.
3. Perform bitwise XOR with num and result evaluated above i.e. num ^
(1 << n);.
#include <stdio.h>
int main()
{
int num, n, newNum;
/*
* Left shifts 1, n times
* then perform bitwise XOR with num
*/
newNum = num ^ (1 << n);
return 0;
}
Output
Happy coding 😉
Recommended posts
report this ad
About Pankaj
Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves
to learn new techs and write programming articles especially for
beginners. He works at Vasudhaika Software Sols as a Software Design
Engineer and manages Codeforwin. In short Pankaj is Web developer,
Blogger, Learner, Tech and Music lover.
Post navigation
←
Previous
C program to clear nth bit of a number
Next
C program to flip all bits of a binary number
→
Pankaj Prakash
Software developer, Blogger, Learner, Music Lover...
Facebook
Twitter
LinkedIn
Google+
C useful resources
C library reference
Learn C programming
The C programming - K&R
The C programming - K&R Pdf
Stack Overflow C
CodeBlocks, Dev C++
C Programming Exercises
Sitelinks
About
Feedback
Testimonials
Write for Us
Privacy policy
Terms of use
Follow us
Facebook
Google
Twitter
Linked In
© 2019 Codeforwin