This is a C Program to swap the ith and jth bits for a 32-bit integer.
This C Program swaps the ith and jth bits for a 32-bit integer.
Take input from the user and swaps the ith and jth bits as shown in the program below.
Here is source code of the C Program to swap the ith and jth bits for a 32-bit integer. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C Program to Swap the ith and jth Bits for a 32-Bit Integer */ #include <stdio.h> #include <stdlib.h> int main (int argc, char *argv[]) { int n = 0, num = 0, p = 0, q = 0; printf ("Enter the number: "); scanf ("%d", &n); printf ("\nEnter position 1: "); scanf ("%d", &p); printf ("\nEnter position 2: "); scanf ("%d", &q); num = n; // see if the bits are same. we use XOR operator to do so. if (((n & (1 << p)) >> p) ^ ((n & (1 << q)) >> q)) { n ^= (1 << p); n ^= (1 << q); } printf ("\nThe result after swapping the respective bits are: %d\n", n); return 0; }
1. In this C Program, we are reading the number using ‘n’ variable and also the bit positions using ‘p’ and ‘q’ variables respectively.
2. First shift the bit in given position to right-end. This can be achieved by the code below.
for p’th bit – n & (1 << p)) >> p)
for q’th bit – (n & (1 << q)) >> q)
3. Next step is to perform XOR operation. If the bits are the same, no need to swap.
4. If the bits are not the same, just toggle the bits. This can be achieved by the code below.
toggle bit at position p: n ^= (1 << p);
toggle bit at position q: n ^= (1 << q);
Test case 1 – Here, the entered number is 1. Postion 1 is 0 & Postion 2 is 1.
./a.out Enter the number: 2 Enter position 1: 0 Enter position 2: 1 The result after swapping the respective bits are: 1
Test case 2 – Here, the entered number is 8. Postion 1 is 0 & Postion 2 is 3.
./a.out Enter the number: 8 Enter position 1: 0 Enter position 2: 3 The result after swapping the respective bits are: 1
Test case 3 – Here, the entered number is 11. Postion 1 is 0 & Postion 2 is 4.
./a.out Enter the number: 11 Enter position 1: 0 Enter position 2: 4 The result after swapping the respective bits are: 26
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Practice Computer Science MCQs
- Buy Computer Science Books
- Watch Advanced C Programming Videos
- Apply for C Internship
- Buy C Books