Perl on Linux – Bitwise Manipulations

Today’s attention is directed at one of the less well known and certainly one of the least understood and used areas of perl. Although direct manipulation of bits is the only thing that a computer really does, programmatic manipulation thereof has been abstracted out for all but the tasks that can only be solved by its use. Still, there are situations and times when it becomes necessary and proper for one bit to dissolve the logical bonds which hold them to the byte and to assume, amongst the operators and variables of the language, an equal station.

Perl bitwise operators are these, six in number:

bitwise logical not   ~
bitwise logical and   &
bitwise logical or    |
bitwise exclusive or  ^
shift right           >>
shift left            <<

Here are some pretty simple examples:

$a = 0555;    # the 0 tells us it's octal (0x would be hex), 
              # so the number is 000 101 101 101
              # in binary.
$b = ~$x;     # here we logically NOT $a, 
              # inverting the bits and giving us 
              # 111 010 010 010
$c = 045;     # 000 000 100 101
$d = $a | $c; # gives us 000 101 111 111
$e = $a & $c; # gives us 000 000 100 000
$f = $a ^ $c; # gives us 000 101 001 101
$g = $a << 1; # shifts the bits 1 place to the left
              # giving us 001 011 011 010
$h = $a >> 1; # shifts the bits 1 place to the right
              # giving us 000 010 110 110

So when would you EVER use this? Well, cryptography uses it since encryption generally deals in bits and bit shuffling. Cryptographics is the card-shark arena of the digital world. Also I have seen this done in a lot of basic, low level systems administration things. Also it is used in places where optimization is paramount and a lot of boolean flags are used, for example, video gaming. Let's look at an example:

$is_red = 01; # in binary : 000 000 000 001
$is_tall = 02; # in binary : 000 000 000 010
$is_thin = 04; # in binary : 000 000 000 100

$bob = 0;

# Bob falls in red paint and is now red!
$bob |= $is_red; # $bob is now 000 000 000 001

# Bob grows 4 meters (cause he's metric and on steroids)
$bob |= $is_tall; # $bob is now 000 000 000 011

# Bob eats subway!
$bob |= $is_thin; # $bob is now 000 000 000 111

# So how do we check bob's status?
# We used OR to get his flags set
# so we use AND to check them

if($bob & $is_tall) { print "bob's tall!"; }
if($bob & $is_thin) { print "bob's thin!"; }
if($bob & $is_red) { print "bob's red!"; }

And that's all there really is to it! Simple, isn't it? Well, play around with it. It's a pretty neat skill and can come in very handy in the weirdest of times...

Leave a Reply