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 onebit elements. It's just that this width is relevant to our example. You could just as easily work with twobit elements:
vec($numbers, 0, 2) = 0b10;
Just make sure that the width is a power of two, and you'll be fine.
blog comments powered by Disqus 






