Write a Binary to Decimal Perl program. Make sure to use very low-level knowledg
ID: 3744207 • Letter: W
Question
Write a Binary to Decimal Perl program. Make sure to use very low-level knowledge to solve this, please.
Don't use the pack / unpack functions of Perl.
Input an integer containing only the digits 0 and 1 (i.e., a binary number) and print its decimal equivalent.
The program should be able to handle input from 1 to 30 digits. We do not need to check the input string for validity (i.e, if all characters entered are 0 s or 1 s); we can assume that the data will be valid.
All input will consist of 0 s and 1 s and will be 1 or more characters long but not longer than 30 characters.
Sample run 1:
Please enter a binary number up to 30 digits: 11111111111
11111111111 is 2047 in decimal.
2:
Please enter a binary number up to 30 digits: 11111111111111111111
11111111111111111111 is 1048575 in decimal.
3:
Please enter a binary number up to 30 digits: 00000000000000000001
00000000000000000001 is 1 in decimal.
4:
Please enter a binary number up to 30 digits: 1
1 is 1 in decimal.
5:
Please enter a binary number up to 30 digits: 10101010101010101010
10101010101010101010 is 699050 in decimal.
6:
Please enter a binary number up to 30 digits: 111111111111111111111111111111
111111111111111111111111111111 is 1073741823 in decimal.
7:
Please enter a binary number up to 30 digits: 111111111111111111111111111110
111111111111111111111111111110 is 1073741822 in decimal.
Explanation / Answer
use strict;
use warnings;
print "Please enter a binary number up to 30 digits: ";
my $binary = <>;
if($binary=~/^.{1,30}$/) # check if input length is between 1 & 30
{
chomp ($binary);
my ($decimal,$bit)=(0,0);
my $index=length($binary)-1;
for ( my $i = 0; $i < length($binary); $i++ ) {
$bit = substr( $binary, $i, 1);
$decimal +=$bit* 2**$index; #For convertion to decimal we need to multiply each bit by 2^{index}
$index--;
}
print " $binary is $decimal decimal. ";
}else{
print " Enter 30 digits only."
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.