Bitwise AND, OR and XOR
Explore bitwise operations AND, OR, and XOR in Bash scripting. Understand how to convert numbers to binary, apply logical operations bit by bit, and interpret results in decimal form. This lesson helps you gain practical skills for manipulating binary data in Bash.
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 ...