Multiple ways to Convert Hexadecimal to/from Number Perl

Learn Perl conversion of Hexa string and numbers with code examples

  • Converted Hexa String to number using the hex function. For example, hex(“0x1”) returns 1.
  • Convert Number to Hexa decimal using the springf function with format %02X

Perl Hexadecimal Number System

Hexadecimal number is also called a Hexa number which contains 16 digits i.e numbers starting from 0,1,2,3,4,5,6,7,8,9,A, B,C,D,E,F. It is based on Base 16. i.e Hexa number system. So Hexa Decimal contains Decimal Numbers,0-9 (base 10) and Extra 6 alphabets - A to F

In Perl, Hexadecimal numbers are always either prefixed with 0x or 0X or normal numbers. For example, the Hexadecimal number is 0x11A or 0X67B,13A.

Decimal Numbers are numbers that contain numbers based on base 10. i.e numbers starting from 0 to 9, Example decimal Number is 25

The below programs take input from a user keyboard console and store it in the corresponding variable.

How to Convert Hexa string to Number in Perl

Perl provides a hex function that converts hexa decimal number into a number variable created with hexa string value. Hexa literal values starts with 0x. passed this value into hex function, returns the number.

Here is an hexa string to number

my $hexa = "x0f1";
my $number = hex($hexa);
print "$number\n";

How to convert Number to Hexa String in Perl

The given number is converted to base 16 Hexa number using the sprintf function.

Sprintf function format value is %02x, that replaced and converted to give value.

Here is an example

my $number = 2545;
my $hexa=sprintf("%02X", $number);
print "$hexa\n";