1. Home

Explore C Tutorials: From Beginner Concepts to Advanced Techniques

Dive into our C tutorials and expand your programming skills. From fundamental concepts to advanced techniques, we've got you covered. Start your journey to C mastery today

• 130 Lessons
• 22 Hours
12.Â

# Bitwise Operators in C

Updated on 19/07/20242,851 Views

## Introduction

Bitwise operators are an essential part of the C programming language, as they help to manipulate individual bits of data at a binary level. From performance optimisation to handling low-level programming, they have been deemed useful for many reasons. On that note, check out this comprehensive guide to the various types of bitwise operators in C and their functionalities.

## Types Of Bitwise Operators In C

There are mainly six types of bitwise operators used in C that allow the manipulation of individual bits of integer types. They are, namely,

• Bitwise AND operator
• Bitwise OR operator
• Bitwise XOR operator
• Bitwise Complement operator
• Bitwise Left Shift operator and
• Bitwise Right Shift operator.

Let's understand each bitwise operators in C program:

## Bitwise AND Operator (&)

The bitwise AND operator is denoted in C, using the & symbol. It is primarily a binary operator, requiring two operands to operate. The bitwise AND operator compares the individual bits of two operands and sets the result bit to 1 only if both corresponding bits are 1; otherwise, it sets the result bit to 0.

Truth Table of Bitwise AND operator in C

 Operand 1 Operand 2 Result--------------------------------0 0 00 1 01 0 01 1 1

### Examples of using the bitwise AND operator in C

Suppose we have two variables named 'a and 'b.' The binary representation of both these variables is

 `a = 12 // 1100 in binaryb = 9 // 1001 in binary`

We now apply the bitwise AND operator on both these variables to compare their individual bits.

 `1100 (a)1001 (b)--------1000 (result)`

According to the truth table, as mentioned above, if both 'a' and 'b' have 1 in their corresponding bit positions, the result will be 1. However, in this case, the result as clearly visible is 1000, which is 8 in decimal.

### Applications of the bitwise AND operator in C

The bitwise AND operator serves multiple purposes in the C programming language.

• Bitwise Flags - The bitwise AND operator is widely used to manipulate and check individual flags within a bit field. By applying the Bitwise AND operator with a specific flag bitmask, you can determine whether a specific flag is set.
• Bitmasking - Bitwise AND operator is useful in extracting specific bits from an integer. By applying the operator with a bitmask representing the desired bits, you can isolate and work with those bits while disregarding the rest.
• Performance Optimisation - The Bitwise AND operator can be used to optimise certain calculations and operations.

## Bitwise OR Operator (|)

The bitwise OR operator performs a bitwise OR operation on the corresponding bits of the two operands. If either or both of the corresponding bits are 1, the result will be 1. Only if both corresponding bits are 0 the result will be 0.

From bit manipulation to bitwise combinations of flags or options, it serves a wide range of functions in the C programming language.

Truth Table

 Operand 1 Operand 2 Result--------------------------------0 0 00 1 11 0 11 1 1

### Examples of using the bitwise OR operator in C

 `#include intÂ main() {Â  Â  unsigned int value = 0x0A; // 00001010 in binaryÂ  Â  unsigned int mask = 0x03; // 00000011 in binaryÂ  Â  unsigned int combinedBits = value | mask;Â  Â  printf("Combined Bits: %X\n", combinedBits);Â  Â  return 0;}`

As mentioned, we have used the bitwise OR operator 'I' to set specific bits in the 'value' variable. The 'mask' variable defines which bits need to be set. We have then performed the 'value I mask' operation, and the result generated is the culmination of the bits from 'value' and 'mask.'

### Applications of the bitwise OR operator in C

Bitwise OR operator has several practical applications. Such include,

Conditional Assignment - Bitwise OR operator can prove to be extremely beneficial in cases where you have to assign values based on specific conditions. It lets you conditionally set bits or combine values based on the expression.

Combining Multiple-Bit Fields - With the help of the Bitwise OR operator, you can also combine multiple-bit fields. It does so by generating a new composite bit field that contains bits from both fields. This is particularly handy when accumulating information from multiple sources or representing a complex set of options using bits.

## Bitwise XOR Operator (^)

Although somewhat similar to the bitwise AND and bitwise OR operators, one major area differentiates the bitwise XOR operator from these two. That bitwise XOR operator performs a bitwise XOR (exclusive OR) operation on the corresponding bits of two operands. This means that if the corresponding bits in the operands are different, the result will be 1. If the corresponding bits are the same, the result will be the same.

Truth Table

 Operand 1 Operand 2 Result--------------------------------0 0 00 1 11 0 11 1 0

As clearly visible, even if one of the corresponding bits of the two operands is 1 and the other is 0, the result generated will also be 1.

### Examples of using the bitwise XOR operator in C

Let's explore this example of how you can use the bitwise XOR operator in C to detect differences between bit patterns.

 `#include intÂ main() {Â  Â  unsigned int pattern1 = 0x0F; // 00001111 in binaryÂ  Â  unsigned int pattern2 = 0x33; // 00110011 in binaryÂ  Â  unsigned int differences = pattern1 ^ pattern2;Â  Â  printf("Differences: %X\n", differences);Â  Â  return 0;}`

Here we have used the bitwise operator XOR' ^' to compare two-bit patterns and compare the differences between them; by enabling 'pattern1 ^ pattern2', the result will be 1 in areas where the corresponding bits are different from each other and 0 where they are the same.

### Applications of the bitwise XOR operator in C

The bitwise XOR operator is commonly used for various purposes. A few examples of the same include,

• Flipping specific bits- By performing a bitwise XOR operation, you can flip specific bits within a value. Bits with 1 in the mask will be converted, whereas those with 0 will remain unchanged.
• Encryption and Cryptography- Bitwise XOR operator also hoards several benefits, especially in encryption and cryptography algorithms. You can use the same on data to encrypt or decrypt information.
• Identifying changes in bit pattern- The bitwise XOR operator can be sued to compare two bits and identify differences (if any) between them. If the result generated is anything other than 0, it denotes that the bit patterns are different.

## Bitwise Complement Operator (~)

The bitwise complement operator is a unary operator that operates on a single operand. It flips each bit of the operand by converting 0s to 1s and 1s to 0s. Here's how it works,

 Operand Result----------------0 11 0

The result of the bitwise complement operation is the inverted value of the operand.

### Examples of using the bitwise complement operator in C

 `#include intÂ main() {Â  Â  unsigned int value = 0x0A; // 00001010 in binaryÂ  Â  unsigned int flippedBits = ~value;Â  Â  printf("Flipped Bits: %X\n", flippedBits);Â  Â  return 0;}`

As clearly visible, we have taken a variable named 'value' and then applied the bitwise complement operator, '~,' to invert all the bits of the variable. The result is the one's complement of the value, wherein each 0 becomes 1, and each 1 becomes 0.

### Applications of the bitwise complement operator in C

Some of the most common applications of bitwise complement operator in C include,

• Bitwise operations and logical operations - The bitwise complement operator is often used alongside the AND operator, and OR operator handles complex bitwise operations. It can also be useful in logical operations, such as logical NOT, where the complemented bits are interpreted as Boolean values.
• Complement Negation - In two's complement representation, the bitwise complement operator is used to perform negation operations by inverting the bits, followed by adding 1.

## Bitwise Left Shift Operator (<<)

As its name implies, the bitwise left shift operator is used to shift the bits of the left operand towards the left by a specified number of positions. The remaining vacant positions on the right are then filled with 0. The bits that get shifted out of the extreme left position are discarded. The syntax for the bitwise left shift operator in C is,

 `operand << number_of_positions`

### Examples of using the bitwise left shift operator in C

 `#include intÂ main() {Â  Â  int value = 10;Â  Â  int multipliedValue = value << 2; // Multiply by 2^2 (4)Â  Â  printf("Multiplied Value: %d\n", multipliedValue);Â  Â  return 0;}`

In this example, we have used the bitwise left shift operator '<<' to shift the value, '10', by '2' positions to the left. The result '40' equals 10 by 2^2 (4).

### Applications of the bitwise left shift operator in C

Some of the many applications of the bitwise left shift operator in C include,

• Implementation of Data Structures - Bitwise left shift operator is used to efficiently implement various data structures and algorithms. For example, it is widely used in trie data structures that use left shifting to manipulate the trie nodes effectively. Furthermore, it is also efficient in bitwise hashing techniques and indexing.
• Packing and Unpacking of Data- When combined with the bitwise OR operator, the bitwise left shift operator can be used to pack multiple values within a single variable. This technique is widely used for protocol design and efficient transmission of data.

## Bitwise Right Shift Operator (>>)

The bitwise right shift operator is used to shift the bits of the left operand to the right by a specified number of positions. The remaining vacant positions are then filled with 0. However, please note that this only holds true for unsigned types. In case you are dealing with signed types, the behaviour is implementation-defined. It means the vacant positions on the left side are filled with copies of the sign bit.

The syntax for the right shift operator is,

 `operand >> number_of_positions`

### Examples of using the bitwise right shift operator in C

 `#include #define FLAG_MASK 0x01Â // 00000001 in binaryintÂ main() {Â  Â  unsigned char flags = 0x0A; // 00001010 in binaryÂ  Â  unsigned char extractedBit = flags >> 2; // Extract the bit at position 2Â  Â  if (extractedBit & FLAG_MASK) {Â  Â  Â  Â  printf("Bit is set\n");Â  Â  } else {Â  Â  Â  Â  printf("Bit is not set\n");Â  Â  }Â  Â  return 0;}`

In the provided example, we have selected a variable named 'flag' with the binary representation of 00001010. Then, we performed the right shift operation, flags >> 2, to extract the bit at position 2. To check if it is set, we have tested the extracted bit against 'FLAG_MASK.'

### Applications of the bitwise right shift operator in C

Here are the most common applications of the bitwise right shift operator in C include,

• Handling signed integers- As stated, for signed integer types, the bitwise right-shift operator in C performs an arithmetic operation. The same can be used for sign extension and maintaining the sign of the value during the right shifts.
• Extraction of Integer Values- By leveraging the power of the bitwise right shift operator, you can conduct efficient extraction of integer values. It is helpful in scenarios where division operators can be replaced with right-shift operations.

## Best Practices and Tips for Using Bitwise Operators

While bitwise operators are powerful tools in the C programming language, using them correctly is crucial to maximising their benefits. Let's take a look at a few practices on how to implement bitwise operators effectively.

### Guidelines for using bitwise operators effectively

• Generate appropriate comments as and when necessary to accurately explain the purpose and intention of bitwise operations.
• Be extra careful while using bitwise operators, especially when handling portable codes consistent with multiple platforms.
• Make use of symbolic constants and masks to increase code readability.
• Conduct frequent tests on your code, especially while dealing with complex bit manipulations.
• Document your code as and when required to help developers understand and maintain the same in the future.

### Tips for avoiding common mistakes when using bitwise operators in C

• Ensure you have a clear knowledge of operator precedence and associativity to avoid any kind of unwanted results or compiled errors.
• Be extra careful about the size and signedness of data types so that they comply with the bitwise operations.
• Handle sign extension carefully, especially when performing the right shift on signed integers.
• Don't go overboard with bitwise operators. If any situation calls for logical operators, use the same instead of bitwise operators.
• Use variable and constant names that clearly state their purpose to reduce the chances of errors or confusion.

## Practice Problems On Bitwise Operators In C

Below are a few practice problems you can check out to further strengthen your knowledge of bitwise operators in C program.

• Write a C program to help find the binary number of a decimal number.
• Write a C program that will reverse bits of a number.
• Write a C program to determine if two integers have opposite signs.
• Write a C program that demonstrates the use of a bitwise right shift operator.

Donâ€™t forget to check out the MS in Machine Learning and AI program offered by upGrad! This program, taught under the guidance of Liverpool John Moores Universityâ€™s invaluable faculty, can be your key to unlocking countless opportunities!

## FAQs

Q1: Can you state the difference between bitwise and logical operators?

One key distinction between bitwise and logical operators is that bitwise operators work on individual bits and produce results in bits, whereas logical operators evaluate Boolean expressions and yield Boolean results based on logical rules.

Q2: Are there any advantages of bitwise operations?

Bitwise operations offer numerous benefits, including increased precision, faster code execution, and improved efficiency in C programming.

Q3: What do we mean by the left shift in C?

Left shift is a bitwise operator in C, represented by the '<<' sign. It is binary in nature. This means that it can only perform operations when two operands are involved.

Test your C programming skills with a Free Quiz

Director of Engineering

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working â€¦Read More

###### Need Guidance? We're Here to Help!
+91
*
By clicking, I accept theT&Cand
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.

Talk to our experts. Weâ€™re available 24/7.

Indian Nationals

1800 210 2020

Foreign Nationals

+918045604032

## Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...