C
  • Introduction
    • Fundamentals of a Program
    • Overview of C
    • Features of C
  • Installing Required Software
    • Setting Up VSCode for Windows
    • Setting Up VSCode for macOS
    • Setting Up VSCode for Ubuntu
  • Starting to write code
    • Compiling and Running Your Code
    • Creating Our First C Program
    • Errors and Warnings
    • Program: Writing a C Program to Display Your Name
    • Structure of a C Program
  • Basic Concepts
    • Comments in C
    • Preprocessor in C
    • The #include Statement
    • Displaying Output
    • Reading Input from the Terminal
    • Enums and Chars
    • Data Types and Variables
    • Format Specifiers
    • Command Line Arguments
    • Program: Calculating the Area of a Triangle
  • Operators
    • Converting Minutes to Years and Days
    • Basic Operators
    • Bitwise Operators
    • Program: Byte Sizes of Basic Data Types
    • cast and sizeof Operators
    • Operator Precedence
  • Control Flow
    • If-Else Statements
    • Program: Weekly Pay Calculation
    • Switch Statement
    • For Loop
    • While and Do-While Loops
    • Nested Loops and Loop Control
    • Program: Guess the Number
  • Arrays
    • Introduction to Arrays
    • Program: Prime Number Generator
    • Multidimensional Arrays
    • Program: simple Weather Program
    • Variable Length Arrays (VLAs)
  • Functions
    • Overview of Functions
    • Defining Functions
    • Arguments and Parameters
    • Returning Data from Functions
    • Variable Scoping
    • Program: Tic Tac Toe Game
    • Recursion
  • Strings
    • Defining a String
    • Constant Strings in C
    • Common String Functions
    • Program: Bubble Sort
    • Searching, Tokenizing, and Analyzing Strings
    • Converting Strings
  • Debugging
    • What is Debugging
    • Understanding the Call Stack
    • Common C Mistakes
    • Understanding Compiler Errors
  • Pointer
    • Defining Pointers
    • Accessing Pointers
    • Program: Pointer Demonstration
    • Pointers and Const
    • Void Pointers
    • String Pointers
    • Array Pointers
    • Utilizing Pointers with Functions
    • Pointer Arithmetic
  • Dynamic Memory Allocation
    • malloc, calloc, and realloc
    • Program: User Input String
    • Memory Deallocation
  • Structure
    • Structures and Arrays
    • Nested Structures
    • Structures and Pointers
    • Structures and Functions
    • Program: Structure pointers and Functions
  • File Input and Output
    • Accessing Files
    • Reading from a File
    • Program: Finding the Total Number of Lines in a Text File
    • Writing to a Text File
    • Finding Your Position in a File
    • Program: Converting Characters in a File to Uppercase
    • Program: Printing the Contents of a File in Reverse Order
  • The Standard C Library
    • Various Functions in C
    • Math Functions in C
    • Utility Functions in C
Powered by GitBook
On this page
  • 1. Bitwise AND (&)
  • 2. Bitwise OR (|)
  • 3. Bitwise XOR (^)
  • 4. Bitwise NOT (~)
  • 5. Left Shift (<<)
  • 6. Right Shift (>>)
  • Practical Scenario: Flag Management
  • Advantages and Disadvantages
  • Conclusion

Was this helpful?

  1. Operators

Bitwise Operators

Bitwise operators in C allow for intricate manipulation of individual bits within integer variables. These operators are fundamental in scenarios requiring efficient binary data manipulation, such as data compression, cryptography, and low-level hardware interaction. Let's delve deeper into each bitwise operator, providing detailed explanations and practical examples.

1. Bitwise AND (&)

Performs a bitwise AND operation on each pair of corresponding bits. It is often used for masking specific bits while preserving others.

Example Application: Setting certain bits to 0 while keeping others unchanged in a variable.

#include <stdio.h>

int main() {
    int original = 14;  // Binary: 1110

    // Applying a mask to keep only the first and third bits
    int result = original & 5;  // Binary: 0101

    // Display the result
    printf("Result after AND operation: %d\n", result);  
    // Result is 4 (binary: 0100)

    return 0;
}

2. Bitwise OR (|)

Performs a bitwise OR operation on each pair of corresponding bits. Useful for combining specific bits.

Example Application: Setting certain bits to 1 while keeping others unchanged in a variable.

#include <stdio.h>

int main() {
    int original = 6;  // Binary: 0110

    // Applying a mask to set the second and fourth bits to 1
    int result = original | 10;  // Binary: 1010

    // Display the result
    printf("Result after OR operation: %d\n", result);  
    // Result is 14 (binary: 1110)

    return 0;
}

3. Bitwise XOR (^)

Performs a bitwise XOR (exclusive OR) operation on each pair of corresponding bits. Useful for toggling specific bits.

Example Application: Toggling the state of certain bits in a variable.

#include <stdio.h>

int main() {
    int flags = 9;  // Binary: 1001

    // Toggling the second and fourth bits
    flags = flags ^ 10;  // Binary: 1010

    // Display the result
    printf("Result after XOR operation: %d\n", flags);  
    // Result is 3 (binary: 0011)

    return 0;
}

4. Bitwise NOT (~)

Inverts the bits of its operand, turning 0s to 1s and vice versa.

Example Application: Creating a bitmask to represent excluded bits.

#include <stdio.h>

int main() {
    int original = 6;  // Binary: 0110

    // Creating a bitmask by inverting the bits
    int bitmask = ~original;  // Binary: 1001

    // Display the result
    printf("Result after NOT operation: %d\n", bitmask);  
    // Result is -7 (binary: 1111)

    return 0;
}

5. Left Shift (<<)

Shifts the bits of the left operand to the left by a specified number of positions.

Example Application: Performing a multiplication by powers of 2.

#include <stdio.h>

int main() {
    int original = 3;  // Binary: 0011

    // Left shifting by 2 positions (multiplying by 4)
    int result = original << 2;  // Binary: 1100

    // Display the result
    printf("Result after left shift: %d\n", result);  
    // Result is 12 (binary: 1100)

    return 0;
}

6. Right Shift (>>)

Shifts the bits of the left operand to the right by a specified number of positions.

Example Application: Performing a division by powers of 2.

#include <stdio.h>

int main() {
    int original = 16;  // Binary: 10000

    // Right shifting by 2 positions (dividing by 4)
    int result = original >> 2;  // Binary: 0010

    // Display the result
    printf("Result after right shift: %d\n", result);  
    // Result is 4 (binary: 0010)

    return 0;
}

Practical Scenario: Flag Management

Consider a scenario where bitwise operators are employed for managing flags in a system.

#include <stdio.h>

// Define flags
#define READ_FLAG 1
#define WRITE_FLAG 2
#define EXECUTE_FLAG 4

int main() {
    // Combining read and write flags
    int permissions = READ_FLAG | WRITE_FLAG;  

    // Checking if execute flag is set
    if ((permissions & EXECUTE_FLAG) != 0) {
        printf("Execute permission granted.\n");
    } else {
        printf("Execute permission not granted.\n");
    }

    return 0;
}

In this example, bitwise OR is used to combine flags, and bitwise AND is used to check if a specific flag is set.

Advantages and Disadvantages

Advantages:

  • Efficient for low-level bit manipulation tasks.

  • Useful for optimizing memory usage in certain scenarios.

  • Enables compact representation of multiple binary flags within a single variable.

Disadvantages:

  • May make code less readable, especially when used excessively.

  • Requires careful handling to avoid undefined behavior, especially with shifting operations.

  • Limited use in high-level programming where abstraction is preferred over direct bit manipulation.

Conclusion

Bitwise operators in C offer powerful tools for intricate bit-level manipulations. Understanding and utilizing these operators can greatly enhance the efficiency and flexibility of your code, especially in scenarios involving low-level data processing.

In the upcoming sections, we'll explore more advanced topics in C programming. If you have specific questions or areas you'd like to delve into further, feel free to ask. Happy coding!

PreviousBasic OperatorsNextProgram: Byte Sizes of Basic Data Types

Was this helpful?