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.

TABLE OF CONTENTS:
  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
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement
 

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
 

blog comments powered by Disqus
   

PERL PROGRAMMING ARTICLES

- 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
- Hashes
- Scalars: Building a Currency Converter
- Scalars and Variables
- Scalars and Boolean and String Operators
- Scalars and Operators
- Scalars


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 7 - Follow our Sitemap

Dev Shed Tutorial Topics: