DSA Course DSA Practice Bitwise Algorithms MCQs on Bitwise Algorithms Tutorial on Biwise Algorithms
Bitwise Operators in C
Last Updated : 11 Oct, 2024
In C, the following 6 operators are bitwise operators (also known as bit
operators as they work at the bit-level). They are used to perform bitwise
operations in C.
1. The & (bitwise AND) in C takes two numbers as operands and does
AND on every bit of two numbers. The result of AND is 1 only if both
bits are 1.
2. The | (bitwise OR) in C takes two numbers as operands and does OR
on every bit of two numbers. The result of OR is 1 if any of the two
bits is 1.
3. The ^ (bitwise XOR) in C takes two numbers as operands and does
XOR on every bit of two numbers. The result of XOR is 1 if the two
bits are different.
4. The << (left shift) in C takes two numbers, the left shifts the bits of
the first operand, and the second operand decides the number of
places to shift.
5. The >> (right shift) in C takes two numbers, right shifts the bits of the
first operand, and the second operand decides the number of places to
shift.
6. The ~ (bitwise NOT) in C takes one number and inverts all bits of it.
Bitwise operators allow precise manipulation of bits, giving you control
over hardware operations. To explore more advanced uses of bitwise
operations and how they apply to data structures, the C Programming
Course Online with Data Structures covers these concepts extensively
with practical examples.
Let’s look at the truth table of the bitwise operators.
X Y X&Y X|Y X^Y
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Example of Bitwise Operators in C
The following program uses bitwise operators to perform bit operations
in C.
// C Program to demonstrate use of bitwise operators
#include <stdio.h>
int main()
{
// a = 5 (00000101 in 8-bit binary), b = 9 (00001001 in
// 8-bit binary)
unsigned int a = 5, b = 9;
// The result is 00000001
printf("a = %u, b = %u\n", a, b);
printf("a&b = %u\n", a & b);
// The result is 00001101
printf("a|b = %u\n", a | b);
// The result is 00001100
printf("a^b = %u\n", a ^ b);
// The result is 11111111111111111111111111111010
// (assuming 32-bit unsigned int)
printf("~a = %u\n", a = ~a);
// The result is 00010010
printf("b<<1 = %u\n", b << 1);
// The result is 00000100
printf("b>>1 = %u\n", b >> 1);
return 0;
}
Output
a = 5, b = 9
a&b = 1
a|b = 13
a^b = 12
~a = 4294967290
b<<1 = 18
b>>1 = 4
Time Complexity: O(1)
Auxiliary Space: O(1)
Interesting Facts About Bitwise Operators
1. The left-shift and right-shift operators should not be used for
negative numbers.
If the second operand(which decides the number of shifts) is a negative
number, it results in undefined behavior in C. For example, results of both
1 <<- 1 and 1 >> -1 are undefined. Also, if the number is shifted more
than the size of the integer, the behavior is undefined. For example, 1 <<
33 is undefined if integers are stored using 32 bits. Another thing is NO
shift operation is performed if the additive expression (operand that
decides no of shifts) is 0. See this for more details.
2. The bitwise OR of two numbers is simply the sum of those two
numbers if there is no carry involved; otherwise, you add their bitwise
AND.
Let’s say, we have a=5(101) and b=2(010), since there is no carry
involved, their sum is just a|b. Now, if we change ‘b’ to 6 which is 110 in
binary, their sum would change to a|b + a&b since there is a carry
involved.
3. The bitwise XOR operator is the most useful operator from a
technical interview perspective.
It is used in many problems. A simple example could be “Given a set of
numbers where all elements occur an even number of times except one
number, find the odd occurring number” This problem can be efficiently
solved by doing XOR to all numbers.
Example
Below program demonstrates the use XOR operator to find odd
occcuring elements in an array.
// C program to find odd occcuring elements in an array
#include <stdio.h>
// Function to return the only odd
// occurring element
int findOdd(int arr[], int n)
{
int res = 0, i;
for (i = 0; i < n; i++)
res ^= arr[i];
return res;
}
int main(void)
{
int arr[] = { 12, 12, 14, 90, 14, 14, 14 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("The odd occurring element is %d ",
findOdd(arr, n));
return 0;
}
Output
The odd occurring element is 90
Time Complexity: O(n)
Auxiliary Space: O(1)
The following are many other interesting problems using the XOR
operator.
1. Find the Missing Number
2. Swap two numbers without using a temporary variable
3. A Memory-Efficient Doubly Linked List
4. Find the two non-repeating elements
5. Find the two numbers with odd occurrences in an unsorted array
6. Add two numbers without using arithmetic operators.
7. Swap bits in a given number
8. Count the number of bits to be flipped to convert a to b
9. Find the element that appears once
10. Detect if two integers have opposite signs
4. The Bitwise operators should not be used in place of logical
operators.
The result of logical operators (&&, || and !) is either 0 or 1, but bitwise
operators return an integer value. Also, the logical operators consider any
non-zero operand as 1. For example, consider the following program, the
results of & & && are different for the same operands.
Example
The below program demonstrates the difference between & and &&
operators.
// C program to Demonstrate the difference between & and &&
// operator
#include <stdio.h>
int main()
{
int x = 2, y = 5;
(x & y) ? printf("True ") : printf("False ");
(x && y) ? printf("True ") : printf("False ");
return 0;
}
Output
False True
Time Complexity: O(1)
Auxiliary Space: O(1)
5. The left-shift and right-shift operators are equivalent to
multiplication and division by 2 respectively.
As mentioned in point 1, it works only if numbers are positive.
Example:
The below example demonstrates the use of left-shift and right-shift
operators.
// program to demonstrate the use of left-shift and
// right-shift operators.
#include <stdio.h>
int main()
{
int x = 19;
printf("x << 1 = %d\n", x << 1);
printf("x >> 1 = %d\n", x >> 1);
return 0;
}
Output
x << 1 = 38
x >> 1 = 9
Time Complexity: O(1)
Auxiliary Space: O(1)
6. The & operator can be used to quickly check if a number is odd or
even.
The value of the expression (x & 1) would be non-zero only if x is odd,
otherwise, the value would be zero.
Example
The below example demonstrates the use bitwise & operator to find if
the given number is even or odd.
C
#include <stdio.h>
int main()
{
int x = 19;
(x & 1) ? printf("Odd") : printf("Even");
return 0;
}
Output
Odd
Time Complexity: O(1)
Auxiliary Space: O(1)
7. The ~ operator should be used carefully.
The result of the ~ operator on a small number can be a big number if the
result is stored in an unsigned variable. The result may be a negative
number if the result is stored in a signed variable (assuming that the
negative numbers are stored in 2’s complement form where the leftmost
bit is the sign bit).
Example
The below example demonstrates the use of bitwise NOT operator.
// C program to demonstrate the use of bitwise NOT operator.
#include <stdio.h>
int main()
{
unsigned int x = 1;
printf("Signed Result %d \n", ~x);
printf("Unsigned Result %u \n", ~x);
return 0;
}
Output
Signed Result -2
Unsigned Result 4294967294
Time Complexity: O(1)
Auxiliary Space: O(1)
Note The output of the above program is compiler dependent
Related Articles
1. Bits manipulation (Important tactics)
2. Bitwise Hacks for Competitive Programming
3. Bit Tricks for Competitive Programming
GeeksforGeeks 488
Previous Article Next Article
Relational Operators in C C Logical Operators
Video | Bitwise Operator in C (AND, OR and XOR)
Similar Reads
Total pairs in an array such that the bitwise AND, bitwise OR and…
Given an array arr[] of size N. The task is to find the number of pairs (arr[i],
arr[j]) as cntAND, cntOR, and cntXOR such that: cntAND: Count of pairs…
7 min read
Maximize count of pairs whose Bitwise AND exceeds Bitwise XOR by…
Given an array arr[] consisting of N positive integers, replace pairs of array
elements whose Bitwise AND exceeds Bitwise XOR values by their Bitwi…
9 min read
Calculate Bitwise OR of two integers from their given Bitwise AND an…
Given two integers X and Y, representing Bitwise XOR and Bitwise AND of
two positive integers, the task is to calculate the Bitwise OR value of thos…
7 min read
Multiply two integers without using multiplication, division and…
By making use of recursion, we can multiply two integers with the given
constraints. To multiply x and y, recursively add x y times. Approach: Since…
9 min read
Largest in array without using conditionals / bitwise / ternary operators
Define a function int max(int a[], int n) which returns the largest integer
from an integer array consisting of n elements (without using conditionals…
4 min read
Check if a number is divisible by 17 using bitwise operators
Given a number n, check if it is divisible by 17 using bitwise operators.
Examples: Input : n = 34 Output : 34 is divisible by 17 Input : n = 43 Outp…
6 min read
Check if a Number is Odd or Even using Bitwise Operators
Given a number N, the task is to check whether the number is even or odd
using Bitwise Operators. Examples: Input: N = 11 Output: Odd Input: N =…
11 min read
Generate first K multiples of N using Bitwise operators
Given an integer N, the task is to print the first K multiples of N using
Bitwise Operators. Examples: Input: N = 16, K = 7 Output: 16 * 1 = 16 16 …
5 min read
Check if a number is divisible by 8 using bitwise operators
Given a number n, check if it is divisible by 8 using bitwise operators.
Examples: Input : 16 Output :YES Input :15 Output :NO Recommended…
4 min read
Complete Reference for Bitwise Operators in Programming/Coding
There exists no programming language that doesn't use Bit Manipulations.
Bit manipulation is all about these bitwise operations. They improve the…
13 min read
Article Tags : Bit Magic C Language C++ DSA +3 More
Practice Tags : CPP Bit Magic cpp-operator
Corporate & Communications Address:-
A-143, 9th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Pradesh
(201305) | Registered Address:- K 061,
Tower K, Gulshan Vivante Apartment,
Sector 137, Noida, Gautam Buddh
Nagar, Uttar Pradesh, 201305
Company Explore
About Us Job-A-Thon Hiring Challenge
Legal Hack-A-Thon
Careers GfG Weekly Contest
In Media Offline Classes (Delhi/NCR)
Contact Us DSA in JAVA/C++
Advertise with us Master System Design
GFG Corporate Solution Master CP
Placement Training Program GeeksforGeeks Videos
Geeks Community
Languages DSA
Python Data Structures
Java Algorithms
C++ DSA for Beginners
PHP Basic DSA Problems
GoLang DSA Roadmap
SQL DSA Interview Questions
R Language Competitive Programming
Android Tutorial
Data Science & ML Web Technologies
Data Science With Python HTML
Data Science For Beginner CSS
Machine Learning JavaScript
ML Maths TypeScript
Data Visualisation ReactJS
Pandas NextJS
NumPy NodeJs
NLP Bootstrap
Deep Learning Tailwind CSS
Python Tutorial Computer Science
Python Programming Examples GATE CS Notes
Django Tutorial Operating Systems
Python Projects Computer Network
Python Tkinter Database Management System
Web Scraping Software Engineering
OpenCV Tutorial Digital Logic Design
Python Interview Question Engineering Maths
DevOps System Design
Git High Level Design
AWS Low Level Design
Docker UML Diagrams
Kubernetes Interview Guide
Azure Design Patterns
GCP OOAD
DevOps Roadmap System Design Bootcamp
Interview Questions
School Subjects Commerce
Mathematics Accountancy
Physics Business Studies
Chemistry Economics
Biology Management
Social Science HR Management
English Grammar Finance
Income Tax
Databases Preparation Corner
SQL Company-Wise Recruitment Process
MYSQL Resume Templates
PostgreSQL Aptitude Preparation
PL/SQL Puzzles
MongoDB Company-Wise Preparation
Companies
Colleges
Competitive Exams More Tutorials
JEE Advanced Software Development
UGC NET Software Testing
UPSC Product Management
SSC CGL Project Management
SBI PO Linux
SBI Clerk Excel
IBPS PO All Cheat Sheets
IBPS Clerk Recent Articles
Free Online Tools Write & Earn
Typing Test Write an Article
Image Editor Improve an Article
Code Formatters Pick Topics to Write
Code Converters Share your Experiences
Currency Converter Internships
Random Number Generator
Random Password Generator
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved