Convert hexadecimal to binary

This Perl CGI script converts hexadecimal to binary. It works by substituting each digit with its binary equivalent.

Try it

Type a hexadecimal number below and run the script.


This is the script for the CGI program above.
use warnings;
use strict;
use CGI;

# Create a hash with keys of hexadecimal digits and values of binary
# digits.  For example, $hex2binary{A} = "1010".

my @hex_digits = (0..9, 'A'..'F');
# Valid hexadecimal digits.
my $valid_hex = join '', @hex_digits;
my %hex2binary;
for (0..15) {
    # Create the binary string for this number.
    $hex2binary{$hex_digits[$_]} = ($_>>3).($_%8>>2).($_%4>>1).$_%2;

# Convert a hexadecimal number to binary by substituting the digits.

sub hex2binary
    my ($hex_string) = @_;
    # Return an undefined value unless the input is hexadecimal.
    return unless $hex_string =~ /^[$valid_hex]+$/i;
    # Globally substitute the hexadecimal digits with binary equivalents.
    $hex_string =~ s/([$valid_hex])/$hex2binary{uc $1}/gi;
    return $hex_string;

# Do the CGI parts

my $cgi = CGI::new ();
my $hex_string = $cgi->param ("hex_string");
print $cgi->header (), $cgi->start_html ();
print "<h1>Hex to binary</h1>\n";
my $binary_string = hex2binary ($hex_string);
if ($binary_string) {
    print "<p>Hexadecimal '$hex_string' is binary '$binary_string'.\n</p>";
} else {
    print "<p>Sorry, I could not understand your input.\n</p>";
print $cgi->end_html ();

Copyright © Ben Bullock 2009-2018. All rights reserved. For comments, questions, and corrections, please email Ben Bullock ( or use the discussion group at Google Groups. / Privacy / Disclaimer