Barry Brevik <> wrote:
> I am running Active Perl 5.8.8 on Windows and am writing a data
> conversion app into which I want to build some debug routines.
>
> To that end, I want to add a routine to take any string and display
> it as hex numbers.
>
> The string can be anywhere from 0 (zero) to over 1,000 characters and
> can contain any byte value from 00 to ff.
>
> I want to do this without adding the overhead of printf or sprintf to
> my program. Has anyone out there done this before?
Probably lots of times. I am not aware of any modules that do this, but
that may be because it is fairly trivial to do in a simplistic way, e.g.
print unpack("H*", $string), "\n";
I also have a function that produces more readable output lying around
that you are welcome to, if it helps, although it uses sprintf. It could
almost certainly be made more efficient, but only if necessary.
# Dump a message in hex (looks a bit like emacs hexl-mode). Parameters
# are the message to dump, and an optional bytes per line (default
# 16). Returns the dumped string ready to print.
sub hex_dump_msg {
my $msg = shift;
my $bpl = shift || 16;
return "" unless defined $msg and $msg ne "";
$bpl > 0 && ($bpl % 2) == 0
or die "Invalid bytes per line ($bpl). Should be positive and
even.\n";
my $res = "";
my $addr = 0;
while ($msg ne "") {
my $seg = substr($msg, 0, $bpl);
substr($msg, 0, $bpl) = "";
my @words = unpack "H4" x ($bpl / 2), $seg;
$res .= sprintf "%04x: ", $addr;
$res .= join(" ", map {pad4($_)} @words);
$seg =~ s/[[:^print:]]/./g;
$res .= " $seg\n";
$addr += $bpl;
}
return $res;
}
sub pad4 {
my $str = shift || "";
return substr("$str ", 0, 4);
}
Only worry about the cost of using [s]printf when it becomes more than
you are prepared to pay.
HTH
--
Brian Raven
This e-mail may contain confidential and/or privileged information. If you are
not the intended recipient or have received this e-mail in error, please advise
the sender immediately by reply e-mail and delete this message and any
attachments without retaining a copy.
Any unauthorised copying, disclosure or distribution of the material in this
e-mail is strictly forbidden.
_______________________________________________
ActivePerl mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs