[comp.lang.perl] Unpack and checksum

lwall@jpl-devvax.jpl.nasa.gov (Larry Wall) (03/14/91)

In article <10509@pogo.WV.TEK.COM> andyd@pogo.WV.TEK.COM (Andy Davidson) writes:
: I am trying to use the snippet of code in the man page to use the unpack
: function to generate a 16-bit checksum, i.e.,
: 
:         while (<>) {
:             $checksum += unpack("%16C*",$_);
:         }
:         $checksum %= 65536;
: 
: However, this reports different results than sum does, either on my 4.3BSD
: VAX or a Sun running SunOS 4.1.  Why?

The BSD sum program isn't a straightforward checksum like the SysV sum
program.  I haven't tried to reproduce the BSD sum algorithm in Perl, since
it's not portable.  The above snippet is equivalent to SysV sum on very
short files, but for longer files, you need this:

	while (<>) {
	    $checksum += unpack("%31C*", $_);
	    $checksum %= 65535;
	}

or

	undef $/;
	$checksum = unpack("%31C*", <>) % 65535;

Note in particular that it's modulo 65535, not 65536.  Blech.

Larry

rbj@uunet.UU.NET (Root Boy Jim) (03/19/91)

(Larry Wall) writes:
?I haven't tried to reproduce the BSD sum algorithm in Perl, since
?it's not portable.

What's not portable about it?
The algorithm, or its implementation in perl?
-- 
		[rbj@uunet 1] stty sane
		unknown mode: sane