On Tue, Apr 17, 2001 at 03:53:39PM -0500, Gray, Brad D wrote:
: Hi,
:
: Is there a way to convert two numbers from decimal to binary, and AND them
: together, and convert the result back to decimal?
It is actually much, much easier than that Brad. Perl has a bitwise
AND operator ( see perlop ):
my $num1 = 5;
my $num2 = 6;
my $result = $num1 & $num2;
Now, if you really want your first two numbers in binary form, you can
try something along these lines:
print &to_binary( $_ )."\n" foreach @ARGV;
sub to_binary($;$) {
my $num = int shift;
my $pad = shift || 8;
my $bin = '';
my $top = 1;
$top *= 2 until $top >= $num;
while ( $top >= 1 ) {
if ( $num >= $top ) {
$bin .= 1;
$num -= $top;
} else {
$bin .= 0;
}
} continue {
$top /= 2;
}
return sprintf "%0${pad}d", $bin;
}
Enjoy!
--
Casey West