How do I convert decimal numbers to binary in Perl?

39,640

Solution 1

$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;

Solution 2

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.

Solution 3

There are a few methods to convert from decimal to binary listed in perlfaq4 (How do I convert between numeric representations/bases/radixes?).

sprintf is a good choice.

Solution 4

I have these aliases in my .bash_profile for quick conversions on the command line:

# from-decimal
alias d2h="perl -e 'printf qq|%X\n|, int( shift )'"
alias d2o="perl -e 'printf qq|%o\n|, int( shift )'"
alias d2b="perl -e 'printf qq|%b\n|, int( shift )'"
# from-hex
alias h2d="perl -e 'printf qq|%d\n|, hex( shift )'"
alias h2o="perl -e 'printf qq|%o\n|, hex( shift )'"
alias h2b="perl -e 'printf qq|%b\n|, hex( shift )'"
# from-octal
alias o2h="perl -e 'printf qq|%X\n|, oct( shift )'"
alias o2d="perl -e 'printf qq|%d\n|, oct( shift )'"
alias o2b="perl -e 'printf qq|%b\n|, oct( shift )'"
# from-binary
alias b2h="perl -e 'printf qq|%X\n|, oct( q|0b| . shift )'"
alias b2d="perl -e 'printf qq|%d\n|, oct( q|0b| . shift )'"
alias b2o="perl -e 'printf qq|%o\n|, oct( q|0b| . shift )'"
Share:
39,640
David
Author by

David

Updated on July 23, 2022

Comments

  • David
    David almost 2 years

    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;
    }