Bitwise Operators In C Programming Explained With Code Examples
Bitwise operators in C programming language provide a powerful way to manipulate individual bits within integers and other data types. This type of operator is essential for bit-level programming tasks such as setting or clearing specific bits, checking the status of bits, or performing efficient arithmetic operations at the bit level. In this article, we will delve into the world of bitwise operators in C, the different types of these operators, the meaning of the operators, and practical use cases.
What Is Bitwise Operator In C?
Bitwise operators in C programming are tools for performing bit-level operations on integer data. These bit operators, including AND (&), OR (|), XOR (^), and NOT (~), allow programmers to manipulate individual bits within binary sequences/ representations. Bitwise operators are commonly used in low-level programming, embedded systems, and various applications that require precise control over data at the binary level, such as encryption, data compression, and hardware interaction. They provide the ability to toggle, set, clear, or analyze specific bits within integers, making them a powerful tool for optimizing code and implementing specialized algorithms.
Use Cases Of Bitwise Operators In C Programming
Bitwise operators are commonly used in computer programming to manipulate individual bits within binary representations of data. They operate at the bit level, allowing you to perform various numerical computations/ operations on individual bits or groups of bits. Here are some common use cases for bitwise operators:
- Masking and Clearing Bits: Bitwise AND and OR operators are commonly used to mask specific bits in a number or set them to a certain value while keeping the other bits unchanged. This is often useful for configuration settings or managing flags.
- Bit Manipulation: XOR is used for toggling individual bits, which can be useful in various applications, such as toggling a state or implementing simple encryption algorithms.
- Bit Counting: Counting the number of set bits (1s) in a binary representation of a number can be achieved by applying bitwise/ bit operations. This is used in various algorithms and data structures.
- Data Compression: Bitwise operations are essential in encryption data compression algorithms, where data is represented as a series of bits/ bit values, and you need to efficiently manipulate and store this data.
- Bitwise Shifts: Left-shift and right-shift operators are used for efficient multiplication and division by powers of 2, making them valuable in optimization and embedded systems programming.
- Cryptography: Building cryptographic algorithms where bitwise operations are essential for data transformation, encryption, and decryption.
- Optimization: Writing efficient code to save memory or improve performance by optimizing data representation and efficient manipulation.
Types Of Bitwise Operators In C
C provides six types of operators that work on bits of integer data, i.e., bitwise operations. In other words, they allow you to perform operations at the bit level and other bit manipulation tasks. These operators work on integer types and treat their operands as sequences of bits. The six common bitwise operators in C are:
- AND Operator (&): The bitwise AND operator performs a logical AND operation on each pair of corresponding bits. It returns 1 if both bit values are 1; otherwise, it returns 0.
- OR Operator (|): The bitwise OR operator performs a logical OR operation on each pair of corresponding bits. It returns 1 if at least one of the bits is 1; otherwise, it returns 0.
- XOR Operator (^): The bitwise XOR (exclusive OR) operator returns 1 if the bits being compared are different; otherwise, it returns 0.
- Complement Operator (~): The bitwise complement operator inverts the bit values. That is, this bit operation turns 0s into 1s and 1s into 0s and returns the complement representation of the number.
- Left Shift Operator (<<): The binary left shift operator moves the bits of a number to the left by a specified number of bit positions. It effectively multiplies the number by 2 to the power of the shift count.
- Right Shift Operator (>>): The right shift operator moves the bits of a number to the right by a specified number of positions. It effectively divides the number by 2 to the power of the shift count.
The table below summarizes the primary bitwise operators and a description of the applications of bitwise operators.
Operator |
Symbol |
Description |
Bitwise AND |
& |
Compares each bit of two operands and returns 1 if both bits are 1, otherwise it returns 0. |
Bitwise OR |
| |
Compares each bit of two operands and returns 1 if either bit is 1, otherwise it returns 0. |
Bitwise XOR |
^ |
Compares each bit of two operands and returns 1 if the bits are different, otherwise it returns 0. |
Bitwise Complement |
~ |
Flips all the bits of an operand, converting each 0 bit to 1 and each 1 bit to 0. |
Left shift |
<< |
Moves the bits of an operand to the left by a specified number of positions, filling in the empty positions with 0. |
Right shift |
>> |
Moves the bits of an operand to the right by a specified number of positions, filling in the empty positions with 0 or 1 depending on the sign of the original value. |
The AND Bitwise Operator In C (&)
The bitwise AND operator is a binary operator that logically ANDs each bit of two operands that are integers. Each bit of the operands is compared, and if both are 1, it returns 1. Otherwise, it returns 0. This bitwise operator in C is represented by a single ampersand sign/ symbol, i.e., (&).
The syntax of the bitwise AND operator is as follows:
operand1 & operand2
Here,
- Operand1 and operand2 refer to the two integer inputs/ variables on which the bitwise low-level operations are to be carried out. Note that the operands can be any integer type, including int, long, short, char, and byte.
- The ampersand sign represents the bitwise operator.
When utilizing the bitwise AND operator, the following conditions or regulations must be met:
- The operands must be of integer types.
- Only integral data types (byte, char, short, int, and long) and not floating-point types can employ the bitwise AND operator.
- The bitwise AND operator always returns an integer value.
- The binary form of the operands serves as the foundation for the bitwise AND operator's output.
Truth Table: The truth table for the bitwise AND operator is given below.
Operand 1 |
Operand 2 |
Result |
0 |
0 |
0 |
0 |
1 |
0 |
1 |
0 |
0 |
1 |
1 |
1 |
Now, let's look at a C program example showcasing the implementation of the AND bitwise operation.
Code Snippet:
Output:
a & b = 1
Explanation:
We begin this simple C program by including the essential input/ output header file in C, i.e., <stdio.h>.
- Then, we define the main() function, which is the entry point for the program's execution.
- Inside main(), we declare two integer variables, x and y, and initialize them with base values of 5 and 3, respectively.
- Next, as mentioned in the code comments, we use the bitwise AND operator (&) to perform a bitwise AND operation on two operands.
- The variable x is initialized with the decimal value 5, which is 101 in binary.
- And y is initialized with the decimal value 3, which is 011 in binary.
- When the bitwise AND operation is performed, comparing the binary representations of x and y bit by bit, the outcome is stored in the result variable, which is 1 (binary 001).
- Then, we use the printf() function to display the value of the result variable. Here, we have a formatted string where the %d format specifier is the placeholder for an integer value, and the newline escape sequence shifts the cursor to the next line.
- Finally, the program returns an exit status of 0, indicating successful execution.
Bookmark this- Compilation In C | A Step-By-Step Explanation & More (+Examples)
The OR Bitwise Operator In C (|)
The bitwise OR operator is a binary operator that logically ORs each bit of two operands that are integers. When comparing the operands, it compares each matching bit, returning 1 if either bit is 1, otherwise returning 0. A single vertical bar or pipe symbol represents it, i.e., (|).
The syntax of the bitwise OR operator is as follows:
operand1 | operand2
Here,
- The two operands are given by the terms operand1 and operand2. The operands can be any integer type, including int, long, short, char, and byte.
- The pipe symbol indicates that we are performing the bitwise OR operation.
When utilizing the bitwise OR operator, the following conditions or rules must be met:
- Both the operands must be of integer types, i.e., integral types (byte, char, short, int, and long), and not floating-point types.
- The bitwise OR binary operator always produces an integer value.
- The binary values/ form of the operands serve as the foundation for the bitwise OR operator's output.
Truth Table: The truth table for the bitwise OR operator is as follows:
Operand 1 |
Operand 2 |
Result |
0 |
0 |
0 |
0 |
1 |
1 |
1 |
0 |
1 |
1 |
1 |
1 |
Code Snippet:
Output:
a | b = 7
Explanation:
We begin the sample C program by including the standard input/output library and defining the main() function.
- Inside the main() function, we declare two integer variables, x and y.
- We initialize x with the decimal value 5, which is 101 in binary, and y with the decimal value 3, which is 011 in binary.
- Then, we use the bitwise OR operator (|) to perform a bitwise OR operation between x and y.
- The result of the bitwise OR operation is stored in the integer variable z. In this case, the result is 7, which is 111 in binary.
- Lastly, we use the printf() function to display the result on the console.
- The program concludes by returning an exit status of 0, indicating that it executed without any errors.
The XOR (Exclusive OR ^) Bitwise Operator In C
The bitwise XOR (exclusive OR) operator is a binary-based operator that logically XORs each bit of two integer operands. It compares each operand's corresponding bit, returning 1 if only one of them is 1, otherwise returning 0.
The syntax of the bitwise XOR operator is as follows:
operand1 ^ operand2
Here,
The operands (1 & 2) are variables/ base values on which we are performing the bitwise XOR operation calculation, with the operator being represented by the hat symbol. The operands can be any integer type, including int, long, short, char, and byte.
When utilizing the binary operator, bitwise XOR, the following conditions or rules must be met:
- The operands can only be integer types (byte, char, short, int, and long), and no floating-point types can be utilized with the bitwise XOR operator.
- The bitwise XOR operation always produces an integer number.
- The binary form of the operands serves as the foundation for the bitwise XOR operator's output.
Truth Table: The truth table for the bitwise XOR operator is as follows:
Operand 1 |
Operand 2 |
Result |
0 |
0 |
0 |
0 |
1 |
1 |
1 |
0 |
1 |
1 |
1 |
0 |
Code Snippet:
Output:
a ^ b = 6
Explanation:
We begin the example C code by including the standard input/output library.
- Inside the main() function, we declare two integer variables, x, and y, and initialize them with base values 5 (binary 101) and 2 (binary 011), respectively.
- Next, we apply the bitwise XOR binary-based operator to perform a bitwise XOR operation between x and y.
- The result of the bitwise XOR operation is stored in the integer variable z. In this case, the result is 6, which is 110 in binary.
- We then use the printf() function to display the result on the console. This displays the string message- a ^ b = 6, to the console, where %d is a placeholder for the value of z.
- The program concludes by returning an exit status of 0, indicating that it executed without any errors.
Complement Bitwise Operator In C (~)
The bitwise complement operator, represented by the tilde symbol (~), performs a logical NOT operation on each bit of an integer operand. It is a unary operator that flips the operand's bits; that is, it turns each 0 bit in the binary representation of the value into a 1 and each 1 into a 0.
The syntax of the bitwise complement operator is as follows:
~operand
Here,
- The tilde symbol (~) represents the complement operator.
- The operand refers to the variable on which we are implementing the complement operation. It can be any integer type, including integer data type, long, short, char, and byte.
When employing the bitwise complement operator, the following conditions or rules must be met:
- The operand must be of the integer type and not floating-point type.
- The bitwise complement operator always yields an integer value.
- The binary form of the operand serves as the foundation for the bitwise complement operator's outcome.
Truth Table: The truth table for the bitwise complement operator is as follows:
Operand |
Result |
0 |
1 |
1 |
0 |
Code Snippet:
Output:
~a = -6
Explanation:
- We declare two integer variables, p and q, inside the main() function of the C code example above.
- Also, we initialize these variables as follows-
- The variable p is initialized with the value of 5.
- In initializing variable q, we use the bitwise complement operator and assign q the value of p's complement. This operation inverts all the bits in p.
- The result of the bitwise complement operation is stored in the integer variable q. In this case, the result is -6.
- We then use the printf() function to display the value of variable q (i.e., the result of the bitwise complement operation calculation) along with a message in the formatted string.
- The program concludes by returning an exit status of 0, indicating that it executed without any errors. The bitwise complement operation on 5 resulted in all bits being inverted, which is why the output is -6.
Check this out- Boosting Career Opportunities For Engineers Through E-School Competitions
Left Shift Bitwise Operator In C (<<)
The bitwise left shift operator (<<) is a binary operation that moves the bits in the left operand by the number of positions provided in the right operand. The leftmost bits are ignored, and the rightmost bits are padded with zeros.
The syntax of the bitwise left shift operator is as follows:
operand1 << operand2
Here,
- The double less than sign represents the shift left operator in Bitwise.
- Operand1 is the left operand, i.e., the value to be shifted, and operand2 is the right operand, which gives the number of positions by which we shift the bits of the left operand.
When employing the bitwise left shift operator, the following conditions or guidelines must be followed:
- The left operand must be of an integer data type (byte, char, short, int, long).
- The right operand must be of an integer data type (byte, char, short, int, long).
- The right operand's value must be non-negative and less than the left operand's bit width. Otherwise, it will lead to undefined behavior.
- Only the bits that fall inside the left operand's range are affected by the shift left operator. Bits that are relocated outside of the range are lost.
- Since the bitwise left shift operator merely moves the left operand's bits to the left by the number of positions provided by the right operand, there is no truth table for this operation.
Code Snippet:
Output:
a <<2 = 20
Explanation:
- Inside the main() function of the example above, we begin by declaring and initializing an integer variable a to the decimal value 5, using the basic assignment operator.
- Next, we declare another variable b and assign it a value by performing a left shift operation on the value of a.
- Here, we use the left shift bitwise operator that shifts the bits of a to the left by 2 positions since a<<2.
- The outcome of the left shift operation is stored in the integer variable b where, the result is 20. The binary representation of 5 (00000101) is shifted two positions to the left, resulting in 20 (00010100) in decimal.
- We then use the printf() function to display this value to the console with a message where %d is a placeholder for the value of b.
- The program concludes by returning an exit status of 0, indicating that it executed without any errors. Note that the left shift operation effectively multiplies the value of a by 2 to the power of 2 (4), resulting in 20.
Shift Right Bitwise Operator In C (>>)
The binary operator bitwise right shift (>>) moves the bits of the left operand to the right by the number of places indicated by the right operand. The sign bit, which is the most important bit of the left operand, is filled in the leftmost bits, leaving the rightmost bits empty.
The syntax of the bitwise right shift operator is as follows:
operand1 >> operand2
The left operand, operand1, is the value to be shifted, and the right operand, operand2, is the number of positions to shift the bits.
When utilizing the bitwise right shift operator, the following requirements or guidelines apply:
- The left operand of the binary right shift operator must be an integral type (byte, char, short, int, or long).
- The right operand's value must be non-negative and less than the left operand's width in bits. If not, the behavior will be undefinable.
- Only the bits that fall within the left operand's range are impacted by the right shift operator. Bits that are moved outside of the range are lost.
- The sign bit is kept during the right shift if the left operand is a signed integer. This indicates that the leftmost bits are filled with 1s if the sign bit is 1 (a negative value); otherwise,
- Since the bitwise right shift operator merely moves the bits of the left operand to the right by the number of places provided by the right operand, there is no truth table for this operation.
Code Snippet:
Output:
a >> 2 = -5
Explanation:
- In the example above, we define an integer variable a with the decimal form value of -20 in the main() function. It is important to note that this value is represented using two's complement binary notation.
- Then, we declare another integer variable, y, and initialize it with the use of the right shift bitwise operator.
- We assign y the value of a after applying the right shift operation on it to the count of 2. That is, the bitwise right shift operator shifts the bits of a to the right by 2 positions.
- The binary representation of -20 (in two's complement form) is shifted two positions to the right, resulting in -5. So, the result in this case is -5, which is stored in the integer variable y.
- Next, we use a printf() statement to display the result on the console along with the message- a >> 2 = -5, where %d is a placeholder for the value of y.
- The program concludes by returning an exit status of 0, indicating that it executed without any errors. Note that the right shift operation effectively divides the value of a by 2 to the power of 2 (4), resulting in -5.
Logical Operators Vs. Bitwise Operators In C
Bitwise operators and logical operators in C serve different purposes and operate at different levels of granularity. Here's a comparison between the two:
Bitwise Operators In C:
- Operate on Bits: Bitwise operators work at the bit level. That is, they perform bit-level manipulation tasks on individual bits within an integer or other integral data types.
- Use Cases: Bitwise operators are typically used for low-level bit manipulation and operations, such as setting, clearing, toggling, or testing specific bits within a variable.
- Operators: Common bitwise operators include AND (&), OR (|), XOR (^), NOT (~), and Bitwise shift operators (<< and >>).
- Result: Bitwise operators return integer results based on bit-level operations. The result is often used for constructing bit patterns, performing flags-based operations, and efficient multiplication/division by powers of 2 using shifts.
- Short-Circuiting: Bitwise operators do not short-circuit. That is, they evaluate all operands, regardless of the result.
Logical Operators:
- Operate on Booleans: Logical operators work with Boolean values (true or false). They are used for making logical comparisons/ performing logical operations to control program flow based on truth values.
- Use Cases: Logical operators are used for making decisions and creating conditional expressions. They are common in if statements, for loops, do-while loops, and other control statements/ structures.
- Operators: Common logical operators include logical AND (&&), logical OR (||), and logical NOT (!).
- Result: Logical operators return Boolean results. That is, they yield true (1) or false (0) based on the logical expression/ condition being evaluated.
- Short-Circuiting: Logical operators can short-circuit. Meaning, they evaluate operands only as necessary. For example, in the logical AND, if the left operand is false, the right operand is not evaluated. For logical OR, if the left operand is true, the right operand is not evaluated.
The table below highlights the key difference between bitwise and logical operators in C programming.
Aspect | Bitwise Operators | Logical Operators |
---|---|---|
Basis of Operation | They operate on individual bits within integers. | They work with boolean variables/ values (0 or 1). |
Operators | AND (&), OR (|), XOR (^), NOT (~), Left Shift (<<), Right Shift (>>) | Logical AND (&&), Logical OR (||), Logical NOT (!) |
Use Case | Bit manipulation, low-level operations | Logical comparisons, control flow |
Result | Integer or bit-wise results | Boolean (true or false) |
Truth Values | 0 represents false, non-zero values represent true | 0 represents false, 1 represents true |
Short-Circuiting | Does not short-circuit (all operands are evaluated) | Short-circuits (operands are only evaluated as necessary) |
Combining Expressions | Can be combined with other bitwise operators | Can be combined with other logical operators |
Example (AND) | result = a & b; (result has bits set where both a and b have bits set) | result = a && b; (result is true if both a and b are true) |
Example (OR) | result = a | b; (result has bits set where either a or b have bits set) | result = a || b; (result is true if either a or b is true) |
Example (NOT) | result = ~a; (result inverts the bits of a) | result = !a; (result is true if a is false, and vice versa) |
In summary, bitwise operators work at the bit level, manipulating individual bits of data. In contrast, logical operators work with true or false conditions and are often used for decision-making and control flow in your C programs.
Also read- Comma Operator In C | Code Examples For Both Separator & Operator
Conclusion
Bitwise operators in C are a fundamental and powerful set of tools for working at the bit level, enabling developers to manipulate data with precision and efficiency. Their applications are diverse, ranging from low-level bit manipulation and bit flag manipulation/ management to efficient bit counting and data compression.
Understanding the fundamentals of bitwise operators opens up new avenues for solving complex problems, optimizing code, and working effectively in fields like embedded systems and cryptography. Bitwise operators are not merely symbols; they represent a gateway to a world of data control and optimization, making them an invaluable asset for programmers irrespective of their level of expertise.
Also read- 100+ Top C Interview Questions With Answers (2023)
Frequently Asked Questions
Q. What are bitwise and logical operators in C?
Bitwise Operators: These operators work at the bit level on the values given as input. They facilitate the bit manipulation techniques applications on the operands as follows:
- Bitwise AND (&): Performs a bitwise AND operation between two operands.
- Bitwise OR (|): Performs a bitwise OR operation between two operands.
- Bitwise XOR (^): Performs a bitwise exclusive OR operation between two operands.
- Bitwise NOT (~): Performs a bitwise negation operation on a single operand, that is, reverses the bits of the binary representation of the operand's input value.
- Left-shift and Right-shift Operators: These operators shift the bits of the left operand to the left and right, respectively, by a specified number of positions given by the right operand.
Logical Operators: The operators perform logical comparisons on two operands. Logical operators operate on boolean values, evaluate expressions, and produce boolean results. Their types are as follows:
- Logical AND (&&): Performs a logical AND operation between two operands.
- Logical OR (||): Performs a logical OR operation between two operands.
- Logical NOT (!): Performs a logical negation operation on a single operand.
Q. What is the difference between the AND (&) and OR (|) bitwise operators?
The AND (&) and OR (|) bitwise operators are fundamental in C for performing bit-level operations. They differ in their behavior as follows:
Bitwise AND (&):
- Purpose: The bitwise AND operator performs a logical AND operation on corresponding bits in two integers. It returns 1 only if both bits being compared are 1; otherwise, it returns 0.
- Use Case: It is commonly used to mask or filter specific bits. If you want to ensure that a particular bit is set to 1 while keeping all other bits unchanged, you can use the bitwise AND operator with a bitmask.
- Example: 0101 & 0011 results in 0001 because only the rightmost bits are both 1 and the rest are 0.
Bitwise OR (|):
- Purpose: The bitwise OR operator performs a logical OR operation on corresponding bits in two integers. It returns 1 if at least one of the bits being compared is 1; otherwise, it returns 0.
- Use Case: It is often used to set or combine bits. If you want to ensure that a particular bit is set to 1 while preserving the other bits, you can use the bitwise OR operator with a bitmask.
- Example: 0101 | 0011 results in 0111 because the rightmost three bits have at least one 1, and they are set to 1 in the result.
Q. What is the symbol of the bitwise operators in C?
The symbols of the bitwise operators in C are as follows:
- Bitwise AND represented by the ampersand sign, i.e., (&).
- Bitwise OR represented by the pipe symbol, i.e., (|).
- Bitwise XOR is represented by the hat symbol, i.e., (^).
- Bitwise NOT, represented by the tilde symbol, i.e., (~).
- Left Shift Bitwise, represented by the double less than sign, i.e., (<<).
- Right Shift Bitwise, represented by double greater than signs, i.e., (>>).
Q. How can bitwise operators in C be used for efficient multiplication and division by powers of 2?
The left shift operator (<<) is used for efficient multiplication, effectively multiplying a number by 2 to the power of the shift count. The right shift operator (>>) is used for efficient division, effectively dividing a number by 2 to the power of the shift count. These operations are valuable for optimization in embedded systems and performance-critical applications.
Q How to add bitwise in C?
In C, you can add two integers using the standard addition arithmetic operator, but bitwise addition doesn't exist as a distinct operation. Bitwise operators, such as & (AND) and | (OR), are used for performing bit-level operations, and they work differently from arithmetic addition.
Here's how you can add two integers using standard arithmetic addition in C:
int a = 5;
int b = 3;
int sum = a + b;
Now, let's look at a simple example that shows how you can perform binary addition using bitwise operators in C.
Code Example:
Output:
a + b = 8
Explanation:
In this code example-
- We begin by defining a binaryAddition function that takes two integer variables and performs binary addition using bitwise operators. Inside the function-
- The while loop first checks the condition if b is not equal to zero.
- If the condition is true, the loop iterates through the bits of a and b to compute the sum (using bitwise XOR) and the carry (using bitwise AND).
- It then uses the left-shit operator to handle carry-over bits and returns the final value of a after iterations are done, and the while condition becomes false.
- Then, inside the main() function, we declare and initialize two integer variables, a with the value 5 (101 in binary) and b with the value 3 (011 in binary).
- Next, we call binaryAddition function to perform binary addition, and the outcome of this operation is stored in the result variable.
- Lastly, we use the printf() statement to display the value of the result variable to the console, and the program terminates with the return 0.
Q. What is the purpose of the bitwise XOR operator (^)?
The XOR bitwise operator in C performs a bitwise exclusive OR (XOR) operation between two integers. Its primary purpose is to compare two binary values, bit by bit, and produce a result in which a bit is set to 1 if the corresponding bits in the operands are different, and it's set to 0 if the bits are the same. The bitwise XOR symbol is a single hat, i.e., (^). Here are some common use cases for the bitwise XOR operator:
- Toggling Bits: XOR is often used to toggle or flip specific bits within an integer expression. If you XOR a number with a bitmask where only one bit is set to 1 (e.g., 1 << n), it will toggle the nth bit, changing 0 to 1 or 1 to 0.
- Simple Encryption: XOR can be used for basic encryption and decryption operations. That is, you can obscure the data by XORing it with a secret key, making it harder to understand without the key.
- Error Detection: XOR can be used in error-checking algorithms, such as checksums and parity checks. If data is altered during transmission, the XOR of the received data and the expected data will yield a non-zero result, indicating a potential error.
- Comparing and Masking: XOR can help identify differences between two data sets, and it can also be used to create bit masks to selectively modify or retrieve specific bits within a value.
By now, you must know all about the bitwise operators in C. Here are a few other important topics you must know:
- 6 Relational Operators In C & Precedence Explained (+Examples)
- Tokens In C | A Complete Guide To 7 Token Types (With Examples)
- Increment And Decrement Operators In C With Precedence (+Examples)
- Constant In C | How To Define & Its Types Explained With Examples
- Identifiers In C | Types, Rules For Definition, & More (+Examples)