#!/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;

