Home Perl Programming Page 3 - Perl, Bit by Bit

# Representing binary numbers - Perl

When you program, you're usually doing it at some distance from the bits and bytes that your computer understands. There never seems to be a need to think about bits. But believe it or not, learning about bits can be to your advantage for certain programming purposes. Perl provides operators for working with bits that let you leverage this knowledge.

Rating:  / 6
August 04, 2009

SEARCH DEV SHED

TOOLS YOU CAN USE

In order to work with bits, we need to be able to represent them in Perl. Perl makes representing binary numbers very easy, just as it makes representing hexadecimal numbers, which are perhaps more commonly used, easy. Suppose that we want to represent a single bit, turned on (1). We'd do it like this:

my \$one = 0b1;

Obviously, this represents the number 1 in base-10. We can represent the numbers 2 and 3 similarly:

my \$two = 0b10;

my \$three = 0b11;

This is confirmed by printing them:

print "\$onen\$twon\$threen";

123

Notice how Perl treats the numbers as base-10 when printing them out. This can be changed:

printf "%bn%bn%bn", \$one, \$two, \$three;

1

10

11

This makes much more sense.

So now you know how to represent a number in binary with Perl. However, that alone doesn't do anything for us. If all you want to do is represent a number, then you're better off just writing the number in base 10, which would certainly save a lot of time.

The real value in thinking in binary is that for each number, what you really have is a string of bits, which can be in one of two states (1 or 0, of course). This is useful for multiple reasons. You might have a string of related boolean values that you need to easily represent. In this case, you're able to pack a lot of values into a very small amount of memory.

Or, you might need to represent some other type of value which the current data types do not suit. For example, you might need to represent something that has four states. This can be done in two bits.

Or, you might need to represent something really big, in which case you need a large number of bits. Using bits, you're only bound by the amount of available memory. Either way, the solution can be found at the bit level.

So, how can we manipulate bits, and how can we determine the value of individual bits? This is done with bitwise operators. Perl offers the typical bitwise operators present in C-style languages. Let's take a look at them now.

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