C programming - bitwise OR operator
The bitwise OR operator |
in C programming is used to perform a bitwise OR operation between two integer operands. It compares the corresponding bits of both operands and sets the resulting bit to 1 if at least one of the bits is 1, and 0 otherwise.
Here is an example of using the bitwise OR operator:
#include <stdio.h> int main() { int num1 = 5; // 101 in binary int num2 = 3; // 011 in binary int result = num1 | num2; printf("result = %d\n", result); return 0; }Sourc.www:etheitroad.com
In this example, we declared two integer variables num1
and num2
and initialized them with the values 5 and 3, respectively. We used the bitwise OR operator to perform a bitwise OR operation between num1
and num2
, and stored the result in the integer variable result
. The binary representation of num1
is 101
, and the binary representation of num2
is 011
, so the result of the bitwise OR operation is 111
, which is equal to 7 in decimal.
The output of the program will be:
result = 7
The bitwise OR operator is useful in situations where we need to set specific bits in an integer to 1. For example, we can use the bitwise OR operator with a mask to set specific bits of an integer to 1.
#include <stdio.h> int main() { int num = 0x0F; // 00001111 in binary int mask = 0x80; // 10000000 in binary int result = num | mask; printf("result = %d\n", result); return 0; }
In this example, we declared an integer variable num
and initialized it with the hexadecimal value 0x0F
, which is equivalent to the binary value 00001111
. We also declared an integer variable mask
and initialized it with the hexadecimal value 0x80
, which is equivalent to the binary value 10000000
. We used the bitwise OR operator to set the most significant bit of num
to 1. The result of the bitwise OR operation is 10001111
, which is equal to 143 in decimal.
The output of the program will be:
result = 143
In summary, the bitwise OR operator |
in C programming is used to perform a bitwise OR operation between two integer operands. It compares the corresponding bits of both operands and sets the resulting bit to 1 if at least one of the bits is 1, and 0 otherwise. The bitwise OR operator is useful in situations where we need to set specific bits in an integer to 1.