Bitwise operators are carried out at the binary level of the operands, within a Byte.
|&||Bitwise AND||$(( a < b ))|
|^||Bitwise Exclusive OR||$(( a <= b ))|
||||Bitwise OR||$(( a == b ))|
|~||Bitwise Complement||$(( a != b ))|
|<<||Left Shift||$(( a > b ))|
|>>||Right Shift||$(( a >= b ))|
Bits are operated upon in each position of their place in a byte.
To demonstrate we need to be able to think of our denary (base 10) numbers in binary form:
- 5 == 0101
- 8 == 1000
- 10 == 1010
- 15 == 1111
#!/bin/bash a=5; echo "Set a to 5, which equates to binary 0101" b=8; echo "Set b to 8, which equates to binary 1000" c=10; echo "Set c to 10, which equates to binary 1010" d=15; echo "Set d to 15, which equates to binary 1111" echo $(( a & d )) echo $(( a ^ b )) echo $(( b | c )) echo $(( ~d )) echo $(( a << 2 )) echo $(( d >> 2 ))
Remember that negative numbers are stored as the two's complement of the positive counterpart. As an example, here's the representation of -2 in two's complement: (8 bits):
The way you get this is by taking the binary representation of a number, taking its complement (inverting all the bits) and adding one. Two starts as 0000 0010, and by inverting the bits we get 1111 1101. Adding one gets us the result above. The first bit is the sign bit, implying a negative.
So let's take a look at how we get ~2 = -3:
Here's two again:
Simply flip all the bits and we get:
|What does -3 look like in two's complement?|
|Start with positive 3:||0000 0011|
|Flip (invert) all the bits to||1111 1100|
|Add one to become negative value (-3),||1111 1101|
So if you simply invert the bits in 2, you get the two's complement representation of -3