Hero Vired Logo
Programs
BlogsReviews

More

Vired Library

Complimentary 8-week Gen AI Course with Select Programs.

Request a callback

or Chat with us on

Home
Blogs
Bitwise Operators in C

Bitwise operators in C are powerful tools that allow programmers to manipulate individual bits within data. These operators perform operations at the bit level, that makes them particularly useful in various applications, including encryption, data compression, and low-level hardware interactions. 

In this guide, we’ll delve into the world of bitwise operators in c, understanding how they work, exploring different types, and examining their practical applications.

 

Table of Contents

 

What are Bitwise Operators?

Bitwise operators in C are special operators that perform operations at the binary level, working with individual bits of data rather than the entire data. These operators can manipulate the individual bits of integral data types, such as integers and characters. They provide a way to perform operations like shifting, ANDing, ORing, XORing, and negating bits, which can be extremely useful in various scenarios. Moreover, you can also learn about What is Arrays in C, C++, Everything you Need to Know for better understanding.

 

How C Bitwise Operators work?

Bitwise operators in C perform operations on the individual bits of the operands. When an operator is applied to two operands, the operation is performed on each pair of corresponding bits. Each bit in the result is determined by applying the operator to the corresponding bits of the operands.

 

Types of C Bitwise Operators

There are six bitwise operators in C:

  • Bitwise AND (&): This operator sets each bit in the result to 1 if and only if both corresponding bits in the operands are 1. Otherwise, the result bit is set to 0.Syntax: result = operand1 & operand2;
  • Bitwise OR (|): The OR operator sets each bit in the result to 1 if either of the corresponding bits in the operands is 1. If both bits are 0, the result bit is set to 0.Syntax: result = operand1 | operand2;
  • Bitwise XOR (^): The XOR operator sets each bit in the result to 1 if the corresponding bits in the operands are different (one bit is 0, and the other is 1). If both bits are the same (both 0 or both 1), the result bit is set to 0.Syntax: result = operand1 ^ operand2;
  • Bitwise NOT (~): The NOT operator is a unary operator that complements (flips) all the operand bits. It changes 0s to 1s and 1s to 0s.
    Syntax: result = ~operand;
  • Left Shift (<<): The left shift operator shifts the bits of the left operand to the left by a specified number of positions, inserting 0s from the right.Syntax: result = operand << n;
  • Right Shift (>>): The right shift operator shifts the bits of the left operand to the right by a specified number of positions, inserting 0s from the left.
    Syntax: result = operand >> n;

 

Exploring Bitwise Operators in C: Shift, AND, OR, XOR, and NOT Operators

  • Bitwise AND (&)

    The bitwise AND operator extracts specific bits from a binary number or sets certain bits to 0 while keeping others unchanged.

    unsigned int a = 60; // Binary: 0011 1100

    unsigned int b = 13; // Binary: 0000 1101

    unsigned int result = a & b; // Binary: 0000 1100

  • Bitwise OR (|)

    The bitwise OR operator is often used to set specific bits to 1 while keeping others unchanged.

    Example:

    unsigned int a = 60; // Binary: 0011 1100

    unsigned int b = 13; // Binary: 0000 1101

    unsigned int result = a | b; // Binary: 0011 1101

  • Bitwise XOR (^)

    The bitwise XOR operator is used to toggle specific bits without affecting other bits.

    Example:

    unsigned int a = 60; // Binary: 0011 1100

    unsigned int b = 13; // Binary: 0000 1101

    unsigned int result = a ^ b; // Binary: 0011 0001

  • Bitwise NOT (~)

    The bitwise NOT operator inverts all the bits of a number.

    Example:

    unsigned int a = 60; // Binary: 0011 1100

    unsigned int result = ~a; // Binary: 1100 0011

  • Left Shift (<<)

    The left shift operator shifts the bits to the left by the specified number of positions.

    Example:

    unsigned int a = 12; // Binary: 0000 1100

    unsigned int result = a << 2; // Binary: 0011 0000

  • Right Shift (>>)

    The right shift operator shifts the bits to the right by the specified number of positions.

    Example:

    unsigned int a = 60; // Binary: 0011 1100
    unsigned int result = a >> 2; // Binary: 0000 1111
    


Click here to learn in detail about the Conditional Operator.

 

Understanding the C XOR Operator: Usage and Examples

The XOR operator benefits various applications, such as flipping bits, checking for parity, and encryption algorithms. It is commonly used to toggle specific bits in a binary number or to perform simple encryption and decryption.

Example: Flipping Bits
unsigned int a = 60; // Binary: 0011 1100
unsigned int mask = 15; // Binary: 0000 1111
unsigned int result = a ^ mask; // Binary: 0011 0011
Example: Checking for Parity
int num = 21; // Binary: 0001 0101
int parity = 0;
while (num) {
    parity ^= num & 1;
    num >>= 1;
}
// At this point, 'parity' will be 1 if the number of set bits in 'num' is odd, and 0 if it's even.

Bitwise Operators in C: Practical Examples and Applications

C Bitwise operators find applications in various practical scenarios:

  • Flag Manipulation: Bitwise operators often set, clear, toggle, and check individual flags or options in a program.
  • Bit Manipulation: Bitwise operators can manipulate individual bits in data structures by setting specific bits in a register to control hardware behavior.
  • Encoding and Decoding: In data compression and encryption, bitwise operations are used to encode and decode data.
  • Checking and Setting Bits: Bitwise operators are employed to check specific bits in a binary number and to set or clear particular bits as needed.
  • Efficient Data Storage: Using bitwise operators, programmers can efficiently pack multiple boolean values into a single integer or use bits to represent different states.

 

Implementing Bitwise Operators in C: A Sample Program

Let’s explore a simple C program that demonstrates the practical use of bitwise operators. Consider a scenario where we want to store the status of four different options in a single integer variable:

  #include 
#define OPTION1 (1 << 0)
#define OPTION2 (1 << 1)
#define OPTION3 (1 << 2)
#define OPTION4 (1 << 3)
int main() {
    unsigned int options = 0;
    // Setting options 1 and 3
    options |= OPTION1;
    options |= OPTION3;
    // Checking if option 2 is set
    if (options & OPTION2) {
        printf("Option 2 is set.n");
    } else {
        printf("Option 2 is not set.n");
    }
    // Toggling option 1
    options ^= OPTION1;
    // Checking all options
    if (options & OPTION1) printf("Option 1 is set.n");
    if (options & OPTION2) printf("Option 2 is set.n");
    if (options & OPTION3) printf("Option 3 is set.n");
    if (options & OPTION4) printf("Option 4 is set.n");
    return 0;
}
This program uses bitwise operators to set, check, and toggle options within the 'options' variable. The OUTPUT will be:
Option 2 is not set.
Option 3 is set.
Option 4 is set.

Bitwise Operators in C: Solving Cryptographic Challenges

Bitwise operators play a significant role in cryptographic challenges and encryption algorithms. They can be used to manipulate and transform data at the bit level, making them crucial for creating secure communication systems.

One classic cryptographic technique that uses bitwise operators is the XOR cipher. The XOR cipher operates by XORing each plaintext character with a specific key to produce the ciphertext. The same key is then used to decrypt the ciphertext and obtain the original plaintext.

Let’s explore a simple implementation of the XOR cipher in C:

#include 
void xorCipher(char *text, char key) {
    while (*text) {
        *text ^= key;
        text++;
    }
}
int main() {
    char plaintext[] = "Hello, World!";
    char key = 'K';
    printf("Original Text: %sn", plaintext);
    xorCipher(plaintext, key);
    printf("Encrypted Text: %sn", plaintext);
    xorCipher(plaintext, key); // Decrypting
    printf("Decrypted Text: %sn", plaintext);
    return 0;
}
In this example, we use the XOR operator to encrypt and decrypt the 'plaintext' using the 'key'. The OUTPUT will be:
Original Text: Hello, World!
Encrypted Text: ┤ØØÛÒÙ<×IÙÙÛ
Decrypted Text: Hello, World!

Mastering Bitwise Logic in C: Advanced Examples and Strategies

Once you grasp the fundamentals of bitwise operators, you can explore more advanced applications. These include:

  • Bit Manipulation Techniques: Advanced bit manipulation techniques, like counting set bits (population count), finding the rightmost set bit, or isolating the least significant bit, can be useful in various algorithms.
  • Bitwise Representations of Data: You can use bitwise operators to represent complex data structures or perform operations like serialization and deserialization.
  • Bitwise Optimization: Bitwise operations can lead to faster and more memory-efficient code in certain situations. For example, bitwise operations can replace some arithmetic calculations.

Conclusion

Bitwise operators in C provide a versatile set of tools for manipulating individual bits within data. They are crucial in various applications, including data compression, encryption, and low-level hardware interactions. By mastering bitwise logic, programmers can enhance their problem-solving skills and optimize code for efficient performance.

 

 

FAQ's

Bitwise operators in C are special operators that allow manipulation of individual bits within data. They include AND, OR, XOR, NOT, left shift, and right shift operators.
There are six bitwise operators in C: AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift (>>).
Bitwise operators find practical applications in flag manipulation, bit manipulation, data encoding and decoding, checking and setting bits, and efficient data storage.
Bitwise operators are supported in many programming languages, including C++, Java, Python, and JavaScript.
Yes, bitwise operators can be used for boolean algebra in C to perform operations like AND, OR, and XOR on boolean values.
Bitwise operators are designed to work on integer data types. They do not apply to floating-point numbers, as they use a different internal representation and require different operations.

High-growth programs

Choose the relevant program for yourself and kickstart your career

You may also like

Carefully gathered content to add value to and expand your knowledge horizons

Hero Vired logo
Hero Vired is a premium LearnTech company offering industry-relevant programs in partnership with world-class institutions to create the change-makers of tomorrow. Part of the rich legacy of the Hero Group, we aim to transform the skilling landscape in India by creating programs delivered by leading industry practitioners that help professionals and students enhance their skills and employability.
Privacy Policy And Terms Of Use
©2024 Hero Vired. All Rights Reserved.
DISCLAIMER
  • *
    These figures are indicative in nature and subject to inter alia a learner's strict adherence to the terms and conditions of the program. The figures mentioned here shall not constitute any warranty or representation in any manner whatsoever.