Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

2. Numbers > 2.15. Converting Binary, Octal, and Hexadecimal Numbers

2.15. Converting Binary, Octal, and Hexadecimal Numbers

Problem

You want to convert a string (e.g., "0b10110“, "0x55“, or "0755“) containing a binary, octal, or hexadecimal number to the correct number.

Perl understands numbers specified in binary (base-2), octal (base-8), and hexadecimal (base-16) notation only when they occur as literals in your programs. If they come in as data—such as by reading from files or environment variables, or when supplied as command-line arguments—no automatic conversion takes place.

Solution

Use Perl’s hex function if you have a hexadecimal string like "2e" or "0x2e“:

$number = hex($hexadecimal);         # hexadecimal only ("2e" becomes 47)

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint