Bitwise Operators in C

Bitwise Operators in C

Bitwise Operators in C allow direct manipulation of individual bits in the integer variables. These operators are fast and efficient, but also prone to errors. These operators are used in various fields, such as low-level programming and embedded systems. In this article, we will discuss what a bitwise operator in C is, its types, applications, advantages and disadvantages of bitwise operators, and how to use these operators in C.

Table of Contents:

What are Bitwise Operators in C?

Bitwise operators in C are the operators that are used to perform bit-level operations on the integers, allowing the direct manipulation of individual bits in a variable. These operators perform the operations by considering the integers as a sequence of binary digits. They are efficient for low-level programming, memory optimization, and hardware interactions. Since these operators work only on a bit at a time, it is different from the arithmetic and logical operators, which work only with entire values.

Types of Bitwise Operators in C

There are six types of bitwise operators in C. Each type shows how to use bitwise operators in C for specific bit manipulations:

Operator Name Symbol Description
Bitwise AND & Sets a bit to 1 if both corresponding bits are 1
Bitwise OR | Sets a bit to 1 if at least one corresponding bit is 1
Bitwise XOR ^ Sets a bit to 1 if the corresponding bits are different
Bitwise NOT ~ Inverts all bits (1 becomes 0, and 0 becomes 1)
Left Shift << Shifts bits to the left, filling with 0s
Right Shift >> Shifts bits to the right, discarding bits

Let’s discuss each of the types of bitwise operators in C briefly, with an example to illustrate how to use bitwise operators in C programming.

1. Bitwise AND (&) Operator in C

The bitwise AND operator in C compares corresponding bits between two integers. It sets a bit to 1 as a result if both corresponding bits are 1; otherwise, it sets the bit to 0.

Syntax:

result = a & b;

Bitwise AND Truth Table:

A B A & B
0 0 0
0 1 0
1 0 0
1 1 1

Example:

C

Output:

Bitwise AND (&) Operator in C

The code shows how the bitwise AND operator in C program performs a bitwise AND operation between the integer 5(00000101) and 3(00000001), which results in 1(00000001) and then is printed to the console.

2. Bitwise OR (|) Operator in C

The bitwise OR (|) operator in C performs a bitwise comparison between two integers and sets each bit to 1 if at least one of the corresponding bits is 1; otherwise, it sets the bit to 0.

Syntax:

result = a | b;

Bitwise OR Truth Table:

A B A | B
0 0 0
0 1 1
1 0 1
1 1 1

Example:

C

Output:

Bitwise OR (|) Operator in C

The code shows how the bitwise OR operator performs a bitwise OR operation on the integers 5(00000101) and 3(00000001), which gives the result 7(00000111) and is then printed to the console.

3. Bitwise XOR (^) Operator in C

The bitwise XOR (^) operator in C compares corresponding bits of two integers and sets each bit to 1 if the corresponding bits are different; otherwise, it sets the bit to 0. The bitwise XOR in C is particularly useful for certain operations like toggling bits.

Syntax:

result = a ^ b;

Bitwise XOR Truth Table:

A B A ^ B
0 0 0
0 1 1
1 0 1
1 1 0

Example:

C

Output:

Bitwise XOR (^) Operator in C

The code shows how the bitwise XOR in C program performs a bitwise XOR operation between the integer 5(00000101) and 3(00000001), which results in 6(00000110) and then is printed to the console.

4. Bitwise NOT (~) Operator in C

The bitwise NOT (~) operator in C inverts all the bits of the integer, which means that it changes 1s to 0s and 0s to 1s. This operation is also known as the one’s complement. Understanding the bitwise NOT in C is important for bit manipulation.

Syntax:

result = ~a;

Example:

C

Output:

Bitwise NOT (~) Operator in C

The code shows how the bitwise NOT operator performs a bitwise NOT operation on the integer 5(00000101), which results in -6(11111010) and then is printed to the console. This negation behavior is characteristic of the bitwise NOT in C.

5. Left Shift (<<) Operator in C

The left shift (<<) operator in C is used to shift the bits of a number to the left by a particular number of positions and fill the vacant rightmost bits with 0s. It multiplies the number by 2^n, where n is the shift count. This is one of the important bitwise shift operators in C.

Syntax:

result = a << n;

Example:

C

Output:

The code shows that the left shift operator shifts the bits of 5(00000101) to the left by 2 positions, which results in 20(00010100) by multiplying 5 by 2^2 and then printing to the console.

6. Right Shift (>>) Operator in C

The right shift (>>) operator in C shifts the bits of an integer to the right by a particular number of positions and discards the rightmost bits. Also, the behavior of the leftmost bits depends on whether the integer is signed or unsigned. This is another basic type of the bitwise shift operators in C.

  • For signed numbers, the behavior of the leftmost bits depends on the system.
  • For unsigned numbers, the leftmost bits are filled with 0.

Syntax:

result = a >> n;

Example:

C

Output:

Right Shift ( data-lazy-src=

The code shows that the right shift operator shifts the bits of 20(00010100) to the right by 2 positions, which results in 5(00000101) by multiplying 20 by 2^2 and then printing to the console.

Bitwise Operator Precedence and Associativity in C

Bitwise operators have lower precedence than arithmetic operators but have higher precedence than logical operators. Also, the bitwise shift operators in C have specific precedence. Knowing the precedence is important for how to use bitwise operators in C correctly in complex expressions.

Here is a table that shows the associativity and precedence of bitwise operators in C:

Symbol Precedence Level Associativity
~ Highest Right to Left
<< High Left to Right
>> High Left to Right
& Medium Left to Right
^ Low Left to Right
| Lowest Left to Right

Key Benefits of Using Bitwise Operators in C

  1. Bitwise operators give higher performance than arithmetic and logical operators.
  2. These operators are ideal for individual bit manipulation.
  3. They provide efficient memory usage by storing multiple Boolean flags in a single variable.
  4. Bitwise operators make it easier to access and modify particular bits in registers and ports.
  5. Bitwise shift operators in C help to perform fast and efficient multiplication and division.
  6. Bitwise operators, especially bitwise XOR in C, are useful in encryption and compression.

Limitations and Disadvantages of Bitwise Operators in C

  1. Bitwise operators are error-prone, as small mistakes in bit manipulation can lead to bugs that are difficult to find.
  2. Using these operators reduces readability as they are hard to read and understand.
  3. Bitwise operators are used only with the integer types and cannot be used with the floating-point type.
  4. The behavior of these operators may vary depending on data type sizes or signed shifts across systems. This is particularly true for bitwise shift operators in C.
  5. Debugging the bitwise operations is very difficult, as they are harder to find.

Real-World Applications of Bitwise Operators in C Programming

  1. Bitwise operators can be used for setting, clearing, and toggling the individual bits by using bitmasks. For example, using the bitwise AND operator in C with a mask can clear specific bits.
  2. The bitwise shift operators in C are used for fast multiplication and division.
  3. These operators efficiently manipulate flags and status registers in a single variable. Especially, the bitwise AND operator in C is often used to check the status of specific flags.
  4. Bitwise XOR in C is used for simple encryption and checksum operations.
  5. They optimize performance in low-level and system-level programming.
  6. Bitwise operators are also used in embedded systems.

Bitwise Operations vs Logical Operations in C

Feature Bitwise Operations Logical Operations
Definition Operate on bits of integers Operate on boolean values (true/false)
Operators & (AND), | (OR), ^ (XOR), ~ (NOT), <<, >> &&, ||, !
Operands Works on integer types (int, char, etc.) Works on expressions that return 0 or non-zero
Result Type Numeric (bit-level result) Boolean (0 or 1)
Evaluation Always evaluates both operands May use short-circuit evaluation
Use Case Used for bitmasking, low-level operations Used for conditional logic and flow control
Example 5 & 3 → 1 (0101 & 0011 = 0001) 5 && 3 → 1 (both are non-zero)

Common Mistakes to Avoid When Using Bitwise Operators

Here are some common mistakes to avoid when using bitwise operators in C:

  • Mixing Up Bitwise and Logical Operators: Using & or | when you meant to use && or || can cause unexpected behavior.
  • Not Using Parentheses for Clarity: Forgetting parentheses may cause the expression to be evaluated in the wrong order.
  • Using Bitwise Operators with Non-Integer Values: Bitwise operators only work with whole numbers like int or char, not with decimals or floating-point numbers.
  • Not Understanding How Right Shift Works: Right shifting a number may behave differently for positive and negative values, especially with signed numbers. This is a common mistake with bitwise shift operators in C.
  • Thinking ~ Works Like a Logical NOT: The bitwise NOT in C flips every bit in a number, not just turns true into false or vice versa.
  • Incorrect Use of Bit Masks: Using the wrong bit mask or forgetting how to set it up properly can give the wrong results.
  • Shifting Bits on Signed Numbers Without Caution: Bit shifting signed values might lead to unexpected results, especially for negative numbers. This is a crucial point regarding bitwise shift operators in C.

Conclusion

Bitwise operators in C can be used for low-level programming and direct manipulation of bits. These operators provide performance and memory optimization. Also, these are fast and efficient, yet they are error-prone, can only be used with integers, and reduce readability. So, by understanding how each bitwise operator works, their applications, advantages, and disadvantages, you can easily perform any bitwise operation without any error in C programming.

Check out other related Software-Engineering blogs:


Macros in C Types of Pointers in C Guide to Efficient Data Compression
Understanding Prim’s Algorithm Palindrome Number in C, Java, and Python HTML Projects for Beginners

FAQs on Bitwise Operators in C

Q1. Can bitwise operators be used with float and double?

No, bitwise operators only work with integer types.

Q2. What’s the difference between & and &&?

& is bitwise AND, and && is logical AND.

Q3. What are the advantages and disadvantages of bitwise operators in C?

Bitwise operators in C offer fast, low-level data manipulation but can reduce code readability and are error-prone if misused.

Q4. What is bitwise NOT in C?

Bitwise NOT in C is an operator that flips all bits of an integer, turning 1s into 0s and 0s into 1s.

Q5. Are bitwise operators faster than arithmetic operators?

Yes, they are generally more efficient.

Q6. What is bitwise AND operator in C?

The bitwise AND operator in C (&) compares each bit of two integers and returns a new value with bits set to 1 only where both bits are 1.

Q7. How to use bitwise operators in C?

Use bitwise operators in C (like &, |, ^, ~, <<, >>) to manipulate individual bits of integer values directly.

Q8. What is the precedence of bitwise operators in C?

The precedence of bitwise operators in C from highest to lowest is: ~, <>, &, ^, then |.

About the Author

Senior Consultant Analytics & Data Science, Eli Lilly and Company

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration.