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;
}
$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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With