Bitwise AND, OR and XOR
Learn how Bitwise AND, OR, and XOR works in detail.
We'll cover the following
Bitwise AND
The bitwise AND operation resembles the logical AND. The result of the logical AND is true
when both operands are true
. Any other operands lead to the false
result.
The bitwise AND operates on numbers instead of boolean expressions. These are steps to perform the bitwise AND manually:
-
Represent the numbers in the two’s complement.
-
If one number has fewer bits than another, add zeros to its left side.
-
Take the bits of the numbers in the same position and apply the logical AND for them.
Here is an example. We want to calculate the bitwise AND for the numbers 5 and 3. First, we should represent their absolute values in binary like this:
5 = 101
3 = 11
The number 3 has fewer bits than 5. Therefore, we have to add an extra zero to its left side. This way, we get the following representation of the number 3:
3 = 011
We should convert a number in the two’s complement if it is negative.
Now, we should apply the logical AND for each pair of bits of the numbers. We can write the numbers in columns for convenience:
101
011
---
001
The result equals 001. We can translate it in decimal this way:
001 = 1
It means that the bitwise AND for numbers 5 and 3 produces 1.
The ampersand sign denotes the bitwise AND operation in Bash. For example, the following command performs our calculations and prints the result:
echo $((5 & 3))
Run the commands discussed in this lesson in the terminal below.
Get hands-on with 1400+ tech skills courses.