Home Perl Programming Page 4 - More Perl Bits

# The vec function - 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

So, how do we work with bit vectors? Fortunately, Perl provides an easy way to do this using the vec function. The vec function, in its most basic usage, returns the bits of a particular element in the bit vector. The function takes three arguments. The first is a string, which is the actual bit vector. You see, using a string as a bit vector allows us to store an arbitrary number of bits, unlike before when we used integers to store things.

The second argument is the index of the element we want to retrieve, and the third argument is the width, in bits, of each element. Note that the width must be a power of two, so you'll need to waste some bits if your data doesn't fit nicely into a proper width.

For example, consider the bit vector we looked at earlier, that represents the numbers 0 through 10 and indicates whether or not each number is prime:

00110101000

(Actually, the bit vector wouldn't quite look this this! But don't worry—that's another topic, and we can get by without discussing it).

If we want to check if the number 2 is prime, we would do so like this:

if (vec(\$numbers, 2, 1)) {

print "2 is prime.n";

}

Above, we retrieve the second element (third in the sequence, since we start counting at zero, just like with arrays) of one bit in width. Since it is 1, we know that 2 is prime.

The vec function can also be used to assign a value to a particular bit or bits. For example, say we wanted to explicitly mark the number 2 as prime. We would do so like this:

vec(\$numbers, 2, 1) = 0b1;

Again, note that you don't have to work with one-bit elements. It's just that this width is relevant to our example. You could just as easily work with two-bit elements:

vec(\$numbers, 0, 2) = 0b10;

Just make sure that the width is a power of two, and you'll be fine.

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