English

# Bitwise Operators in Perl

What are the Bitwise Operators in perl?

## Explanation

The following are the bitwise operators.
 Operator Function << Binary shift left >> Binary shift right & Bitwise AND | Bitwise OR ^ Bitwise XOR ~ Bitwise NOT

The basic criterias for the bitwise shift operators is that the operands should be numerals, but these are represented as binary internally.

### Bitwise Shift Right & Left:

The bitwise shift right operator shifts the specified bits to the right or left. First we convert both operands to binary then shift bits to right or left.The binary digits equivalent decimal is the result.

#### Example :

#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
\$a=40;
\$b=2;
\$c;
\$d;
\$c = \$a>>\$b;
print "Binary Shift Right:";
print "<br>";
printf "Binary after shifting right \$a>>\$b = %03bn", \$c;
print "<br>";
printf "Decimal after shifting right \$a>>\$b = %dn", \$c;
print "<br>";
print "Binary Shift Left:";
print "<br>";
\$d = \$a<<\$b;
printf "Binary after shifting left \$a<<\$b = %03bn", \$d;
print "<br>";
printf "Decimal after shifting left \$a<<\$b = %dn", \$d;
Result :

Binary Shift Right:
Binary after shifting right 40>>2 = 1010
Decimal after shifting right 40>>2 = 10
Binary Shift Left:
Binary after shifting left 40<<2 = 10100000
Decimal after shifting left 40<<2 = 160

The AND operator is used to compare two operands, if both bits are 1 it returns 1, otherwise it returns 0.The other bitwise operators have the same semantics as their logical operator counterparts except the truth value is represented by 1 and 0 for true and false respectively.

The OR operator returns true if either one of the bits are 1.The XOR operator returns trueif both the operands are different. The NOT operator inverts all bits say 0's to 1's and vice versa

#### Example :

#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
\$a=3;
\$b=9;
\$c;
\$d;
\$e;
\$c = \$a & \$b;
printf "Binary value of \$a & \$b = %30b<br>",\$c;
printf "Decimal Equivalent of \$a & \$b =%d<br>",\$c;
\$d = \$a | \$b;
printf "Binary value of \$a | \$b = %30b<br>",\$d;
printf "Decimal Equivalent of \$a | \$b =%d<br>",\$d;
\$e = \$a ^ \$b;
printf "Binary value of \$a ^ \$b = %30b<br>",\$e;
printf "Decimal Equivalent of \$a ^ \$b =%d<br>",\$e;
Result :

Binary value of 3 & 9 = 1
Decimal Equivalent of 3 & 9 =1
Binary value of 3 | 9 = 1011
Decimal Equivalent of 3 | 9 =11
Binary value of 3 ^ 9 = 1010
Decimal Equivalent of 3 ^ 9 =10