Difference between revisions of "Generate 8bit dec to hex to bin chart.pl"

From Alteeve Wiki
Jump to navigation Jump to search
(Created page with "{{howto_header}} A short script that generates a byte-length chart of decimal to hexadecimal to binary values. <source lang="perl"> #!/usr/bin/perl # Author: Madison Kelly; mkelly@alteeve.com # 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 lea...")
 
 
Line 3: Line 3:
A short script that generates a [[byte]]-length chart of [[decimal]] to [[hexadecimal]] to [[binary]] values.
A short script that generates a [[byte]]-length chart of [[decimal]] to [[hexadecimal]] to [[binary]] values.


<source lang="perl">
<syntaxhighlight lang="perl">
#!/usr/bin/perl
#!/usr/bin/perl
# Author:  Madison Kelly; mkelly@alteeve.com
# Author:  Madison Kelly; mkelly@alteeve.com
Line 40: Line 40:


exit;
exit;
</source>
</syntaxhighlight>


{{footer}}
{{footer}}

Latest revision as of 23:55, 15 August 2023

 Alteeve 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.

#!/usr/bin/perl
# Author:  Madison Kelly; mkelly@alteeve.com
# 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.
Us: Alteeve's Niche! Support: Mailing List IRC: #clusterlabs on Libera Chat
© Alteeve's Niche! Inc. 1997-2023   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.