How to convert binary to decimal and vice versa in Perl?


The conversion between binary to decimal and decimal to binary is a necessity when it comes to dealing with binary data and using them in some simple applications. In Perl, we can convert from decimal to binary and vice versa in multiple ways.

In this tutorial, we will explore different examples where we will first convert a decimal value into a binary value and then a binary value into a decimal value.

Decimal to Binary in Perl

Let's first see an example where we are given two decimal values and we want to convert them to their binary representation.

For example, let's say we have two numbers, "x = 154" and "y = 10", and we want a program that takes these two numbers and convert them to their binary representations. Consider the code shown below that does the same.

Example

In this code, we are using the unpack function and then removing the trailing zeroes and returning the string.

sub decimal2binary {
   my $str = unpack("B32", pack("N", shift));
   $str =~ s/^0+(?=\d)//;
   return $str;
}
@res = decimal2binary(154);
print "Binary representation of 154 is: ", @res;
print "\n";
@res = decimal2binary(10);
print "Binary representation of 10 is: ", @res;

Output

If you run the above code on a Perl compiler, you will get the following output in the terminal −

Binary representation of 154 is: 10011010
Binary representation of 10 is: 1010

Binary to Decimal in Perl

Now let's consider another example, where we will convert binary numbers into decimals. Consider the code shown below that does the same. Here, we are converting the binary numbers "154" and "10" to their decimal representation

Example

sub binary2decimal {
   return unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
}
@res = binary2decimal('10011010');
print "Decimal representation of 10011010 is: ", @res;
print "\n";
@res = binary2decimal('1010');
print "Decimal representation of 1010 is: ", @res;

Output

If you run this code on a Perl compiler, you will get the following output in the terminal −

Decimal representation of 10011010 is: 154
Decimal representation of 1010 is: 10

Conclusion

In this tutorial, we used two examples to demonstrate how you can convert binary numbers to their decimal counterparts and vice versa in Perl.

Updated on: 04-Apr-2023

468 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements