10 Lines of code are more than enough. This teaser challenges you to perform the daunting task of hex dumping under 10 lines of code.

The Challenge

The code should read input from STDIN, and print hex values of each input octet to the STDOUT. The code should also prints all printable characters, and print all non-printable characters as ‘.’ (dot). The length of each output line should be modifiable.
Note: As in all other Top 10 Lines challenges, thou shell not exceed 10 lines of code.

Code Maestro’s Teaser

9 lines of Perl are more than enough:

$len = 0xC; #12 bytes in each time
for( $offset = 0; read STDIN, $chars, $len; $offset += $len)
{
    $printable = $chars;
    $printable =~ s/[^x21-x7e]/./g; #Replace non printable chars with dot
    #Pad the chars to $len size, and ord them
    @hex = unpack("C*", $chars. "" x ($len - length $chars));
    printf("%.8X: "."%.2x " x $len ."| %sn", $offset, @hex, $printable);
}

Your Kung-Fu is better than the Maestro’s? Submit your code

Code Challenge - Any language acceptable, no technique too dirty!

Posted by Ami Chayun | |

1 Comment »

  1. Your code has a few problems.

    1) It has an incredibly minimal definition of “non-printable” characters
    2) It improperly handles the last line - I believe the intent was to use $len in the unpack as a measure of the bytes actually read, this would require reading the return value of “read()”.
    3) It also doesn’t print the last line correctly (since some of the bytes may not exist - but we still want the “|” char to line up.

    I suggest the following 4 line rewrite:

    for( $offset = 0; $len = read STDIN, $chars, 12; $offset += $len) {
    @hex = unpack(”C*”, $chars);
    $chars =~ y/-\37\177-\377/./;
    printf(”%.8X: “.”%.2x ” x $len .” “x(12-$len).”| $chars\n”,$offset, @hex);
    }

    Amusing challenge, but I believe this demonstrates that my kung-fu is better than the Maestro’s. For more kludgy examples, feel free to peruse my code (mostly perl) at MarginalHacks

    Comment by David Madison — February 29, 2008 @ 5:35 am

RSS feed for comments on this post. TrackBack URI

Leave a comment