Generate 8bit dec to hex to bin

From AN!Wiki
Jump to: navigation, search

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

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

Download the perl source:

# Author:  Digimer;
# 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:
        # 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";


Any questions, feedback, advice, complaints or meanderings are welcome.
Us: Alteeve's Niche! Support: Mailing List IRC: #clusterlabs on Freenode   © Alteeve's Niche! Inc. 1997-2019
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.
Personal tools