• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » C » Operator » Bitwise Operators in C
Next →
← Prev

Bitwise Operators in C

By Dinesh Thakur

All the objects stored in a computer are ultimately converted into binary numbers, sequences of 0s and 1s. Each digit in a binary number store on one bit of the computer memory. A bit define as the smallest unit of memory in a computer. The computer manipulates a number by manipulating the bits on which the number stored. In control systems also we often need to use operators to manage bits.

The Bitwise operators in C also called bit-level programming used for manipulating individual bits in an operand. Bit by bit works on one or several bit patterns or binary numerals at the individual bit level. It is used in numerical calculations to speed up the process of computation. It is used extensively in embedded software. 

Note: Bitwise Operators can only apply on char and integer operands. We cannot use bitwise operators with float, double, long double, void, and other user define complex data types.

The C language provides six bitwise operators to manipulate the bit patterns of integral values (integers and characters). They include not, i.e., complement(~), and (&), or (|), exclusive or, i. e., xor (^), left shift (<<) and right shift (>> ). These operators work directly on the bit patterns of the operands, i. e., on sequences of bits (0 and 1) representing the operands. In addition, C language provides five compound assignment operators (&=,| =, ^=, <<= and >>=).

The complement operator (~) is a unary prefix operator and is used, as in ~a, whereas all other operators are binary infix operators and used as in a op b.

First, consider these bitwise operations on individual bits. The bitwise and operator evaluates as 1 if both operands are 1, and zero otherwise. The bitwise or operator evaluates as 1 if either or both operands is 1, and zero otherwise. The bitwise xor operator evaluates as 1 if either of the operands (but not both) is 1, and zero otherwise. Finally, the bitwise not operator complements the operand’s value, i. e., and it returns 1 if the operand is zero and vice versa. These operations summarize in Table.

Table Evaluation of bitwise operators on 1 bit values

While working with integral numbers, the bitwise operations performed on all bits. As we know, char values represented using 1 byte (i. e., 8 bits), int values using either 2 or 4 bytes, short int using 2 bytes, and long int using 4 bytes. These values may be signed or unsigned. However, binary operators’ working illustrated here using 4-bit numbers a and b having decimal values 11 (binary 1011) and 7 (binary 0111), respectively.

The bitwise and, or and xor operations performed on corresponding bits of two integer operands by applying bit operations, as shown in Table. Thus, a & b (i. e., 1011 & 0111) evaluates as 0011, i.e., decimal 3 as shown in Fig. Also, a | b evaluates as 1111(decimal 15), and a ^ b evaluates as 1100 (decimal 12).

Fig. Effect of bitwise and, or and xor operators on 4-bit unsigned int numbers a=11 and b=7

The complement operation performs on all the bits of a number. Thus, the expression ~a evaluates as 0100 (decimal 4). This complement operation is also called 1’s complement. The left shift (<<)and right shift (>>) are binary infix operators used, as in val << n and val >>n. They shift the bits in the first operand (val) by several bit positions specified in the second operand (n).

When a value shifted left, the empty bit positions on the right filled with 0 bits; the bits that move out of the number are lost. Thus, expression a << 1 left-shifts bit in variable a (binary 1011) by 1-bit position to obtain 0110. (decimal 6) and expression a << 2 left-shifts bits in variable a by 2-bit positions to get 1100 (decimal 12) as shown in Fig.

Fig Effect of bitwise not, left-shift and right-shift operators on 4-bit int numbers (variable a is an unsigned int and c is a signed int)

The working of the right shift operator depends on whether the number shifted is signed or unsigned. When an unsigned number shifted to the right, the empty bit positions on the left (i. e., MS bits) filled with 0 bits. This shift is called the logical right shift. Also, note that the bits that move out of a number are lost. For example, assuming that variable a (binary 1011) is an unsigned int variable, the expression a>> 1 evaluates as 0101 (decimal 5) and a>> 2 as 0010 (decimal 2).

When a signed int shifted to the right, the bits shifted as usual, except that the MS bit copied to itself. Thus, the empty MS bit positions all become equal to the sign bit. This shift is called the arithmetic right shift. For example, assuming a (binary 1011) and b (binary 0111) to be signed int variables, the expression a >> 2 evaluates as 1110, and expression b >> 2 evaluates as 0001.

Observe that a right shift by 1-bit position is equivalent to integer division by 2. Also, a left shift by 1-bit position is equivalent to multiplication by 2, provided the most significant bit of the number shifted is 0.

The bitwise compound assignment operators are similar to other compound assignment operators. For example, the assignment expression a & = expr is equivalent to the expression a= a & (expr).

We’ll be covering the following topics in this tutorial:

  • Precedence and Associativity of Bitwise Operators
  • Set, Reset and Complement a Specific Bit
  • Testing Bits

Precedence and Associativity of Bitwise Operators

The bitwise complement operator is a unary operator and has the precedence and associativity as other unary operators. Thus, its precedence is higher than the arithmetic operators, and it has right-to-left associativity.

All other bitwise operators have left-to-right associativity. The precedence of the bitwise shift operators is just below that of the arithmetic operators and higher than that of the relational operators. The bitwise and, xor and or operators have precedence (in that order) below that of the equality operators (== and ! =) and above that of the logical operators (&& and ||).

Finally, the bitwise compound assignment operators ( &=, ^=, |=, <<= and >>=) have the precedence and associativity as other assignment operators. Thus, they have precedence below that of the conditional operator (? 🙂 and above that of the comma operator (,) and right-to-left associativity.

Set, Reset and Complement a Specific Bit

Let us now understand how we can set, reset, or complement a specific bit at position pin a given number without affecting other bits in it. For this, we need to perform a particular bitwise operation between the given number and another value called a mask.

The mask should usually have the same size in bits as that of the number operated. One of two masks will use depending on the operations to perform. One mask has 1 bit at position p and 0 bit at all other positions, and another mask with 0 bit at position p and 1 bit at all other positions. For example, for operations on bit position 2, we require either 0000 0100 or 1111 1011 as the mask.

These masks can quickly obtain using the bitwise left shift operation on number 1, which has a bit pattern of 0000 0001, i.e., 1 bit at bit position 0 and 0 bit at all other positions. Thus, to obtain a mask with 1 at bit position p and 0 at all other positions, we use the expression 1<< p. We can complement this mask to obtain a mask with 0 at bit position p and 1 at all other positions using the expression ~ (1<< p).

Now, to set a bit at position p in a given number num, without affecting other bits in it, we use the bitwise or value of a with a mask having bit 1 at position p and 0 at all other positions, as shown in Fig, using the following statement.

num = num | (1 << p);

Note that the parentheses in the above expression are redundant but they improve readability. Alternatively, we can use the compound assignment operator |= as shown below.

num | = 1 << p; /* set bit at position p */

 Fig. Set, reset and complement a bit at position 2 without affecting other bits in number num (* indicates any bit value, either 0 or 1).

We can use the above mask and the bitwise xor operator to complement (toggle) a bit at Position p without affecting the other bits as

num ^ = 1 << p; /* complement bit at position p */

To reset a bit at position p without affecting the other bits in a given number num, we need to perform a bitwise and operation between num and the mask having 0 bit at position p and 1 at all other positions using the following statement.

num &=~(1 << p); /* reset bit at position p */

Testing Bits

To test the value of a bit at position p in number num, we check the condition num & (1<< p). If this expression is non-zero, the bit at position p set; otherwise, it is 0.

We can perform this test on all bits of a given number num using a loop, as shown below.

Note that the parentheses in the test for the statement are essential as the > operator has higher precedence than the & operator. Alternatively, we can write this test simply as

if (num & mask)

If the mask has same size (in bits) as that of num, we can alternatively write the above for loop in a concise manner by eliminating loop variable bas shown below.

for(mask = 1; mask > 0; mask<<= 1) {  
 if (num & mask) {  
  /* bit b is 0, perform desired operation */  
}  
 else { 
  /* bit b is 1, perform desired operation */  
 } 
}

Sometimes we may wish to process the bits in a given number from left to right. For this, we need to take a mask with a 1 bit in the MS bit position and 0 at all other bit positions. This can be achieved by shifting number 1 left as shown below.

mask= 1 << (8 * sizeof(mask) - 1)

Note that to shift this bit right one bit position at a time, we have to use a logical right shift operation in which the empty MS bit positions created by the right shift are set to 0. Hence, mask should be declared as an unsigned variable.

Example of test the bits in a number

a) Count the number of zeros and ones in a binary representation of a number

A program to count zeros and ones in a binary representation of a number is given below.

#include<stdio.h>
int main() {
 int num;
 int zeros, ones;
 int b, mask;
 printf("Enter an integer number: ");
 scanf ("%d",&num);
 ones = 0;
 mask = 1;
 for(b = 0; b < 8 * sizeof(num); b++) {
  if (num & mask)
    ones++;
    mask <<= 1;
 }
  zeros= 8 * sizeof(num) - ones;
  printf("Zeros: %d Ones: %d\n", zeros, ones);
  return 0;
} 

We can also write a function count_lbits to count the number of ones in the binary representation of a number as shown below.

int count lbits(int num) {
int ones, mask;
ones = 0;
for(mask = 1; mask > 0; mask<<= 1) {
  if (num & mask)
    ones++;
}
 return ones;
}

You’ll also like:

  1. Bitwise Operators in Java Example
  2. Bitwise AND, OR, and XOR Operators in Java Example
  3. Which bitwise operator is suitable for checking whether a particular bit is ON or OFF
  4. Write A C++ Program To Comparing Integers Using If Statements, Relational Operators And Equality Operators.
  5. What is Operators? Explain Scope Resolution Operator and Operators Precedence.
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

C Programming

C Programming Tutorials

  • C - History
  • C - Anatomy
  • C - Constants
  • C - Identifiers
  • C - Data Types
  • C - Libraries File
  • C - Header Files
  • C - Basic Language
  • C - Data Types Sizes
  • C - Header Files Importance
  • C - Escape Sequences
  • C - Main() Purpose
  • C - Program Procedure
  • C - Control Statements
  • C - Enumeration Constant
  • C - Add numbers
  • C - Return Statement
  • C - Avoid Goto
  • C - Command Line Arguments
  • C - Switch Case
  • C - Switch Case Limitations
  • C - getchar() and putchar()
  • C - Iteration Statements
  • C - Pass by Value and Reference
  • C - Structures and Unions
  • C - Structure
  • C - Dynamic Memory
  • C - Fgets and Fputs Functions
  • C - Gets() and Puts() Functions
  • C - Armstrong Number
  • C - Storage Classes
  • C - Fibonacci Series
  • C - Precision Setting
  • C - const Parameters

C - Variable & It's Type

  • C - Variables
  • C - Variable Lifetime
  • C - Static Variable
  • C - Register Variable
  • C - Global Variables
  • C - Auto Variables
  • C - Local Variables

C - Operator & Expressions

  • C - Operator
  • C - Boolean Operators
  • C - Bitwise Operator
  • C - Arithmetic Operators
  • C - Modulus Operator
  • C - Ternary Operator
  • C - Expressions
  • C - Arithmetic Expressions

C - Array

  • C - Arrays
  • C - Array Types
  • C - Array Characteristics
  • C - Static Arrays
  • C - Global Arrays
  • C - 3D Arrays
  • C - Dynamic Arrays
  • C - Pointer to 3D Arrays
  • C - Array Elements Hold
  • C - Arrays as Function Parameters
  • C - Accessing Matrix Elements
  • C - File Handling
  • C - Matrix Multiplication
  • C - Dynamic Memory Allocation

C - Searching & Sorting

  • C - Data Structures
  • C - Linear Search
  • C - Bubble Sort
  • C - Merge Sort
  • C - Linked List
  • C - Insertion Sort
  • C - Binary Search
  • C - Selection Sort
  • C - Quick Sort

C - Functions

  • C - Functions
  • C - Functions Advantages
  • C - Void Functions
  • C - Function Call
  • C - Default Return Value
  • C - String functions

C - Pointer

  • C - Pointers
  • C - Type Casting Of Pointers
  • C - Pointer Advantages
  • C - Pointers Initialization
  • C - Vectors and Pointers

C - Differences

  • C - C Vs C++
  • C - Formal Args. Vs Actual Args.
  • C - Keywords Vs Identifiers
  • C - Strings Vs Character Arrays
  • C - Address Vs Dereference Operator
  • C - Goto Vs longjmp
  • C - Declaring Vs Defining Variable
  • C - String Vs Array
  • C - Call by Value Vs Reference
  • C - Structure Vs Union
  • C - For Vs While loops
  • C - Compiler Vs Interpreter

C - Programs

  • C Program Standard Deviation
  • C Program Calculate Tax
  • C Program Sum Series
  • C Program Merge Arrays
  • C Program Euclid’s Algorithm
  • C Program Print Weekdays
  • C Program Sum of Digits
  • C Program Print a list
  • C Program Print Pythagorean
  • C Program Quiz program
  • C Program Display Table
  • C Program Print Comma-Separated
  • C Program Prints Prime Numbers
  • C Program for Print Integer
  • C Program Count Number
  • C Program Print Color Name
  • C Program Print Odd Numbers
  • C Program Calculate area
  • C Program for a Menu
  • C Program Add Two Vectors
  • C Program Array Addresses
  • C Program Division by Zero Error
  • C Program Compare two Dates
  • C Program Tower of Hanoi
  • C Program return 3 Numbers
  • C Program for Prime Numbers
  • C Program for Factorial
  • C Program for Palindrome

Other Links

  • C Programming - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW