: What I was looking for was the unpack equivalent of:
: ####
: my $string = 'ThisIsAString';
: my $chksum = 0;
:
: for( split(//,$string) )
: {
: $chksum += ord;
: }
:
: print sprintf("%X",$chksum)."\n";
: ####
You're right there! Well, sort of. See below.
$ cat try
#!/usr/local/bin/perl -w
use strict;
use warnings;
sub explicit_checksum {
my $str = shift;
my $sum = 0;
$sum += ord for split // => $str;
$sum;
}
sub unpack_checksum {
unpack "%16C*", shift;
}
my $string = 'ThisIsAString';
my $chksum = 0;
for (split //, $string) {
$chksum += ord;
}
my @method = (
[ explicit => \&explicit_checksum ],
[ unpack => \&unpack_checksum ],
);
for (@method) {
my($name,$code) = @$_;
printf "%-10s %X\n", $name . ":", $code->($string);
}
$ ./try
explicit: 50C
unpack: 50C
These results match coincidentally. Given a long enough $string, i.e.,
one whose ASCII values sum greater than 0xFFFF, only the least
significant sixteen bits would match.
For example:
$ cat try
[...]
open my $fh, '/etc/lynx.cfg' or die "$0: open /etc/lynx.cfg: $!";
my $string = join '', <$fh>;
[...]
$ ./try
explicit: ADA3B4
unpack: A3B4
The unpack isn't equivalent, but that's because the checksum your code
computes doesn't follow the convention of producing a result clamped
to a certain number of bits, e.g., $sum & 0xFFFF for a 16-bit checksum.
: I thought "%H*" would handle that (if "H*" gives a concat of the hex
: values then "%H*" should give sum, right?), but then comparing "H*"
: with "C*":
Remember that H returns hex strings, but C returns unsigned char
values. Which of these matches the values returned from Perl's ord
operator?
: On the other hand "%C*" *does* return the checksum (in decimal).
No, it doesn't return a value in a particular base, just a number.
Base is a representation, e.g., input and output, issue. Yes, I
realize it's almost certainly a twos-complement bitpattern in some
register in your machine, but we're speaking at the level of
abstraction of the Perl programming language, not the bare metal.
: I've read and reread the perlfunc for pack and unpack and I'm now
: pretty confused.
I hope this helps you through the confusion.
Greg