Pages

Thursday, April 7, 2011

Perl

I've also been learning Perl in my spare time, since its the only programming language it seems I can use at work. Well, aside from Java and VBA, but I mean for command line stuff. I'm studying the book thats available for free on the Perl website, and one of the excercises suggested i figure out how to convert decimal to binary using eight bitwise "and" operators. I figured it out (mostly) myself, thoguh I used a hint about the binary representation of the powers of two. Check it out, I think its a pretty clever hack.
#!/usr/bin/perl
#dec2bin.plx
use warnings;
use strict;
print "Enter a decimal number ";
my $num=;
print(
($num & 128) <=> 0,
($num & 64) <=> 0,
($num & 32) <=> 0,
($num & 16) <=> 0,
($num & 8) <=> 0,
($num & 4) <=> 0,
($num & 2) <=> 0,
($num & 1) <=> 0,
"\n");
It works becuase Perl converts all numebrs into their binary representation, and the bitwise "and" operator compares numbers bit by bit. The binary representations of the powers of 2 all start with 1 and the rest are zeros. So you build up a string that becomes a binary number by &'ing each of the powers of two as high as needed, as these get compared with the binary representation of the input number. Its not the most straightforward way, especially since the input number is apparently already being used in binary internally, but neat none the less.

No comments: