Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Hex dump

by kschwab (Priest)
on Sep 10, 2001 at 19:08 UTC ( #111481=snippet: print w/replies, xml ) Need Help??
Description: subroutine to print a hexdump of a string. I saw some discussion in the CB about needing such a thing.

Update: Also see HexView by OeufMayo.

sub hdump {
    my $offset = 0;
    foreach my $data (unpack("a16"x(length($_[0])/16)."a*",$_[0])) {
        if ($len == 16) {
            @array = unpack('N4', $data);
            $format="0x%08x (%05d)   %08x %08x %08x %08x   %s\n";
        } else {
            @array = unpack('C*', $data);
            $_ = sprintf "%2.2x", $_ for @array;
            push(@array, '  ') while $len++ < 16;
            $format="0x%08x (%05d)" .
               "   %s%s%s%s %s%s%s%s %s%s%s%s %s%s%s%s   %s\n";
        $data =~ tr/\0-\37\177-\377/./;
        printf $format,$offset,$offset,@array,$data;
        $offset += 16;

Update: Fixed the map() in a void context problem. Thanks merlyn. For the curious, it sort of evolved into a void context as I cleaned up the subroutine before posting it to perlmonks.
Replies are listed 'Best First'.
Re: Hex dump
by merlyn (Sage) on Sep 11, 2001 at 02:01 UTC
    I really dislike the "void map" there, for things like:
    map {$_ = sprintf('%2.2x',$_)} @array;
    What's wrong with simply:
    $_ = sprintf "%2.2x", $_ for @array;
    It even comes in at fewer characters, as well as running faster!

    -- Randal L. Schwartz, Perl hacker

Re: Hex dump
by tokai (Initiate) on Aug 29, 2015 at 00:06 UTC

    I liked the output of this function, so I used it for debugging purposes for a while... but in the end I wrote my own simplified variant with some other ideas from here and there which produces exactly the same output:

    sub hexdump($) { my $offset = 0; foreach my $chunk (unpack "(a16)*", $_[0]) { my $hex = unpack "H*", $chunk; # hexadecimal magic $chunk =~ tr/ -~/./c; # replace unprintables $hex =~ s/(.{1,8})/$1 /gs; # insert spaces printf "0x%08x (%05u) %-*s %s\n", $offset, $offset, 36, $hex, $chunk; $offset += 16; } }
Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://111481]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (13)
As of 2016-10-26 10:11 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (339 votes). Check out past polls.