Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert decimal numbers to binary in Perl?

I am trying to make a program that converts decimal numbers or text into binary numbers in Perl. The program asks for user input of a character or string and then prints out the result to the console. How do I do this? My code I have been working on is below, but I cannot seem to fix it.

print "Enter a number to convert: ";
chomp($decimal = <STDIN>);
print "\nConverting $number to binary...\n";
$remainder = $decimal%2;
while($decimal > 0)
{
    $decimal/2;
    print $remainder;
}
like image 602
David Avatar asked May 12 '10 17:05

David


2 Answers

$decimal/2; isn't affecting $decimal

You probably want $decimal /= 2; or if you want to be cool, then $decimal >>= 1;

But really, really, you probably just want:

printf "%b\n", $decimal;

like image 156
David M Avatar answered Oct 12 '22 05:10

David M


Try this for decimal-to-binary conversion:

my $bin = sprintf ("%b", $dec);

To get each bit:

my @bits = split(//, $bin);

Then you can manipulate each bit, change the MSB index and so on.

like image 37
user2461880 Avatar answered Oct 12 '22 06:10

user2461880