Binary, Octal, and Hexidecimal Numbers in Perl

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. See below example

#!/usr/bin/perl -w
use strict;
use warnings;

my $hexadecimal = 0x2e;
my $octal = 057;
my $binary = 0b101110;

print “Hexadecimal: “,$hexadecimal ,”, Octal: “,$octal,” Binary: “,$binary;

#Hexadecimal: 46, Octal: 47 Binary: 46

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.

If you want to convert a string (e.g., “0b10110”, “0x55”, or “0755”) containing a binary, octal, or hexadecimal number to the correct number, use Perl’s hex function if you have a hexadecimal string like “2e” or “0x2e”:

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

Use the oct function if you have a hexadecimal string like “0x2e”, an octal string like “057”, or a binary string like “0b101110”:

$number = oct($hexadecimal);         # "0x2e" becomes 46
$number = oct($octal);               # "057" becomes 47 
$number = oct($binary);              # "0b101110" becomes 46

The oct function converts octal numbers with or without the leading “0”; for example, “0350” or “350”. Despite its name, oct does more than convert octal numbers: it also converts hexadecimal (“0x350”) numbers if they have a leading “0x” and binary (“0b101010”) numbers if they have a leading “0b”. The hexfunction converts only hexadecimal numbers, with or without a leading “0x”: “0x255”, “3A”, “ff”, or “deadbeef”. (Letters may be in upper- or lowercase.)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s