Generate 8bit dec to hex to bin chart.pl

From Alteeve Wiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

 AN!Wiki :: How To :: Generate 8bit dec to hex to bin chart.pl

A short script that generates a byte-length chart of decimal to hexadecimal to binary values.

Download the perl source: generate_8bit_dec_to_hex_to_bin_chart.pl.

#!/usr/bin/perl
# Author:  Digimer; digimer@alteeve.ca
# Date:    Jun. 21, 2010
# License: GPLv2

# Be clean
use strict;
use warnings;

# Headers
print " Dec. | Hex.  | Binary\n";
print "------+-------+-----------\n";
foreach my $dec (0..255)
{
        # Convert the decimal to hexadecimal and pad the result with a leading
        # zero if needed.
        my $hex = sprintf("%x", $dec);
        $hex=length($hex) == 1 ? "0".$hex : $hex;

        # Adapted from: http://docstore.mik.ua/orelly/perl/cookbook/ch02_05.htm
        # Convert the decimal to a network-byte value then back to a bit-by-bit
        # value. This generates a longer string than I want, so regex out the
        # last two nibbles and put them back together with a space to make it
        # more readable.
        my $bin=unpack("B32", pack("N", $dec));
        my ($l, $r)=($bin=~/(\d{4})(\d{4})$/);
        $bin="$l $r";

        # Pad the decimal value with spaced to right-justify the value and then
        # print the three values.
        $dec=length($dec) == 1 ? "  ".$dec : length($dec) == 2 ? " ".$dec : $dec;
        print " $dec  |  $hex   | $bin\n";
}
print "------+-------+-----------\n";

exit;

 

Any questions, feedback, advice, complaints or meanderings are welcome.
Alteeve's Niche! Enterprise Support:
Alteeve Support
Community Support
© Alteeve's Niche! Inc. 1997-2024   Anvil! "Intelligent Availability®" Platform
legal stuff: All info is provided "As-Is". Do not use anything here unless you are willing and able to take responsibility for your own actions.