Home Perl Programming Page 2 - More Perl Bits

# Bit shift operators - Perl

In the last article, I talked about the need to work at the bit level in Perl and in other languages. In order to understand bits, we first took a look at how binary numbers are represented in Perl, and then we took a look at two bitwise operators, AND and OR. In looking at the operators, we looked at their most common uses in programming. We also began to look at an algorithm for finding prime numbers, but we stopped upon seeing that there is no easy implementation, at least not without a knowledge of bits.

Rating:  / 1
September 14, 2009

SEARCH DEV SHED

TOOLS YOU CAN USE

Let's now take a look at the bit shift operators. A bit shift operator simply shifts bits around, as its name implies. Perl offers the left bit shift operator, represented by two leftward-pointing angle brackets (<<), and the right bit shift operator, represented by two rightward-pointing angle brackets (>>).

Suppose I have a binary number that looks like this:

11110000

If I shift everything to the right four bits, I get this:

1111

Here's what this looks like in Perl:

printf "%bn", 0b11110000 >> 4;

Then, if I shift everything back to the left four bits, I get this:

11110000

As you can see, zeros are brought in to fill the new space.

Here's the operation in Perl:

printf "%bn", 0b1111 << 4;

If, instead, I had shifted things to the right four more bits, I would get 0. The bits would simply “fall off the edge.” Once again, this is what this would look like in Perl:

printf "%bn", 0b1111 >> 4;

 >>> More Perl Programming Articles          >>> More By Peyton McCullough