A bitwise operator is an operator which used to perform bitwise operations on bit patterns. It converts the operands into binary data and then perform necessary operations bit by bit. Bitwise operators are of 6 types,
Bitwise AND ( & ) :
A Bitwise AND operator performs binary AND operation bit by bit on the operands.
It converts the given input to binary digit and then perform AND operation bit by bit. Finally it returns the decimal value.
BOR=$(( $val1 | $val2 ))
echo Bitwise OR of $val1 and $val2 is $BOR
Run the file,
jhony@ljlinux:~$ ./bor.sh
Enter val1 : 36
Enter val2 : 72
Bitwise OR of 36 and 72 is 108
Bitwise XOR ( ^ ) :
Bitwise ^ operator performs binary XOR operation bit by bit on the operands.
It converts the given input to binary digit and then perform XOR operation bit by bit. It compares both operands and returns 1 if both are different and it returns 0 if both the operands are same. Finally it returns the decimal value of the result.
BXOR=$(( $val1 ^ $val2 ))
echo Bitwise XOR of $val1 and $val2 is $BXOR
Run the file,
jhony@ljlinux:~$ ./bxor.sh
Enter val1 : 42
Enter val2 : 27
Bitwise OR of 42 and 27 is 49
Bitwise compliment ( ~ ) :
Bitwise ~ operator performs binary NOT operation bit by bit on the operand.
It converts the given input to binary digit and then perform XOR operation bit by bit. It operator is used to invert all of the bits of the operand and returns the decimal value of the result.
Remember it inverts 32 bits of an operand.
Example:
Let us find the Bitwise compliment of 36.
The binary value for 36 is,
36 - 0000000000000000000000100100
~36 - 1111111111111111111111011011
The decimal value for 1111111111111111111111011011 is -36.
For this we can use Bitwise compliment operator ~ in shell script.
Open a file as bcom.sh
$ vim bcom.sh
Paste the below code
Code:
#!/bin/sh
#Getting input
read -p 'Enter the value : ' val
BCOM=$(( ~$val ))
echo Bitwise compliment of $val is $BCOM
Run the file,
jhony@ljlinux:~$ ./bcom.sh
Enter the value : 36
Bitwise compliment of 36 is -37
Right Shift ( >> ) :
The Right Shift operator shifts the bits of the left operand to right by number of times specified.
It moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0.
For better understanding the Right shift operator always decrease the value of the operand.
Example:
Let us shift the values one, two and three times to the right.
Comments