Path: utzoo!news-server.csri.toronto.edu!rutgers!mcnc!decwrl!elroy.jpl.nasa.gov!jpl-devvax!lwall From: lwall@jpl-devvax.jpl.nasa.gov (Larry Wall) Newsgroups: comp.lang.perl Subject: Re: Unpack and checksum Message-ID: <1991Mar13.230853.20862@jpl-devvax.jpl.nasa.gov> Date: 13 Mar 91 23:08:53 GMT References: <10509@pogo.WV.TEK.COM> Reply-To: lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) Distribution: usa Organization: Jet Propulsion Laboratory, Pasadena, CA Lines: 30 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