Up to this point, the operators worked on numbers in the way we think of them. However, as we already know, computers don’t see numbers the same as we do; they see them as a string of bits. These next few operators perform operations on numbers one bit at a time—that’s why we call them bitwise operators. These aren’t used quite so much in Perl as in other languages, but we’ll see them when dealing with things like lowlevel file access. First, let’s have a look at the kind of numbers we’re going to use in this section, just so we get used to them:
Does it surprise you that 10101010 (170) is twice as much as 01010101 (85)? It shouldn’t, when we multiply a number by 10 in base 10, all we do is slap a 0 on the end, so 21 becomes 210. Similarly, to multiply a number by 2 in base 2, we do exactly the same. People think of bitwise operators as working from right to left; the rightmost bit is called the least significant bit and the leftmost is called the most significant bit. The AND Operator The easiest bitwise operator to fathom is called the and operator, and is written &. This compares pairs of bits as follows:
For example,51 & 85looks like this: 51 00110011 Sure enough, if we ask Perl the following: #!/usr/bin/perl w print "51 ANDed with 85 gives us ", 51 & 85, "\n"; it’ll tell us the answer is 17. Notice that since we’re comparing one pair of bits at a time, it doesn’t really matter which way around the arguments go,51 & 85is exactly the same as85 & 51. Operators with this property are called associative operators. Addition (+) and multiplication (*) are also associative: 5 * 12 produces the same result as 12 * 5. Subtraction (–) and division (/) are not associative: 5 – 12 does not produce the same result as 12 – 5. Here’s another example—look at the bits, and see what you get: 51 00110011 The OR Operator As well as checking whether the first and the second bits are 1, we can check whether one or another is 1, the or operator in Perl is . This is how we would calculate204  85: 204 11001100 Now we produce 0s only if both the bits are 0; if either or both are 1, we produce a 1. As a quick rule of thumb,X & Ywill always be smaller or equal to the smallest value ofXandY, andX  Ywill be bigger than or equal to the largest value ofXorY. The XOR Operator What if you really want to know if one or the other, but not both, are one? For this, you need the exclusive or operator, written as the ^ operator: 204 11001100 Please check back next week for the third part of this article.
blog comments powered by Disqus 






