
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
Swapping numbers using bitwise operator in C
Problem
How to swap the numbers using the bitwise operator in the C programming language?
Solution
The compiler swap the given numbers, first, it converts the given decimal number into binary equivalent then it performs a bitwise XOR operation to exchange the numbers from one memory location to another.
Algorithm
START Step 1: declare two variables a and b Step 1: Enter two numbers from console Step 2: swap two numbers by using BITWISE operator a=a^b b=a^b a=a^b Step 3: Print a and b values STOP
Program
#include<stdio.h> int main(){ int a,b; printf("enter the values for a and b:"); scanf("%d%d",&a,&b); printf("value of a=%d and b=%d before swap
",a,b); a= a^b; b= a^b; a= a^b; printf("value of a=%d and b=%d after swap",a,b); return 0; }
Output
enter the values for a and b:24 56 value of a=24 and b=56 before swap value of a=56 and b=24 after swap Explanation: a=24 binary equivalent of 24 =011000 b=56 binary equivalent of 56= 111000 a= a^b = 100000 b=a^b=100000 ^ 111000 =011000 a=a^b=100000 ^ 011000 = 111000 Now a=111000 decimal equivalent =56 b= 011000 decimal equivalent = 24
- Related Articles
- Maximum of four numbers without using conditional or bitwise operator in C++
- Multiply any Number with using Bitwise Operator in C++
- Add two numbers using ++ operator in C++.
- Bitwise AND of Numbers Range in C++
- What is Bitwise AND Operator (&) in JavaScript?
- What is Bitwise NOT Operator (~) in JavaScript?
- What is Bitwise OR Operator (|) in JavaScript?
- What is Bitwise XOR Operator (^) in JavaScript?
- Bitwise right shift operator in Java\n
- What is JavaScript Bitwise AND (&) Operator?
- What is JavaScript Bitwise OR (|) Operator?
- What is JavaScript Bitwise NOT(~) Operator?
- What is JavaScript Bitwise XOR (^) Operator?
- What is Bitwise Left Shift Operator (
- What is Bitwise Right Shift Operator (>>) in JavaScript?

Advertisements