Home arrow Perl Programming arrow 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.

  1. More Perl Bits
  2. Bit shift operators
  3. Bit vectors
  4. The vec function
  5. Finding prime numbers
By: Peyton McCullough
Rating: starstarstarstarstar / 1
September 14, 2009

print this article



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:




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




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:




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

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates


Dev Shed Tutorial Topics: