Created
November 19, 2021 21:10
-
-
Save mwgamera/b3c8f51baf2978b81d2dcde9259625f9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
# klg, Nov 2021 | |
use strict; | |
# POSIX cksum(1) uses CRC with the same polynomial | |
# as Zlib but MSB-first while Zlib uses it reversed | |
# and starts from ~0 instead of appending the length. | |
# So one can be computed in terms of the other by | |
# reversing bits appropriately. | |
use Compress::Zlib 'crc32'; | |
use constant BUF_SIZE => 4096; | |
unless (@ARGV) { | |
cksum(\*STDIN); | |
exit 0; | |
} | |
my $e = 0; | |
for my $n (@ARGV) { | |
if ($n eq '-') { | |
cksum(\*STDIN, $n); | |
next; | |
} | |
eval { | |
$e++; | |
open my $f, '<', $n or die $!; | |
cksum($f, $n); | |
close $f or die $!; | |
$e--; | |
}; | |
warn "$n: $@" if $@; | |
} | |
exit !!$e; | |
sub cksum { | |
my ($file, $name) = @_; | |
my $s = 0xffffffff; | |
my $c = 0; | |
local $/ = \BUF_SIZE; | |
local $_; | |
binmode($file) or die $!; | |
while (<$file>) { | |
$c += length; | |
$s = crc32(bitswap($_), $s); | |
} | |
for ($_ = '', my $k = $c; $k; $k >>= 8) { | |
$_ .= chr($k & 0xff); | |
} | |
$s = crc32(bitswap($_), $s); | |
$s = $s >> 1 & 0x55555555 | ($s & 0x55555555) << 1; | |
$s = $s >> 2 & 0x33333333 | ($s & 0x33333333) << 2; | |
$s = $s >> 4 & 0x0f0f0f0f | ($s & 0x0f0f0f0f) << 4; | |
$s = $s >> 8 & 0x00ff00ff | ($s & 0x00ff00ff) << 8; | |
$s = $s >> 16 | ($s & 0xffff) << 16; | |
printf("%u %u%s\n", $s, $c, $name ? " $name" : ''); | |
} | |
sub bitswap { | |
local $_ = shift; | |
y/\x01-\xfe/\x80\x40\xc0\x20\xa0\x60\xe0\x10\x90\x50\xd0\x30\xb0\x70\xf0\x08\x88\x48\xc8\x28\xa8\x68\xe8\x18\x98\x58\xd8\x38\xb8\x78\xf8\x04\x84\x44\xc4\x24\xa4\x64\xe4\x14\x94\x54\xd4\x34\xb4\x74\xf4\x0c\x8c\x4c\xcc\x2c\xac\x6c\xec\x1c\x9c\x5c\xdc\x3c\xbc\x7c\xfc\x02\x82\x42\xc2\x22\xa2\x62\xe2\x12\x92\x52\xd2\x32\xb2\x72\xf2\x0a\x8a\x4a\xca\x2a\xaa\x6a\xea\x1a\x9a\x5a\xda\x3a\xba\x7a\xfa\x06\x86\x46\xc6\x26\xa6\x66\xe6\x16\x96\x56\xd6\x36\xb6\x76\xf6\x0e\x8e\x4e\xce\x2e\xae\x6e\xee\x1e\x9e\x5e\xde\x3e\xbe\x7e\xfe\x01\x81\x41\xc1\x21\xa1\x61\xe1\x11\x91\x51\xd1\x31\xb1\x71\xf1\x09\x89\x49\xc9\x29\xa9\x69\xe9\x19\x99\x59\xd9\x39\xb9\x79\xf9\x05\x85\x45\xc5\x25\xa5\x65\xe5\x15\x95\x55\xd5\x35\xb5\x75\xf5\x0d\x8d\x4d\xcd\x2d\xad\x6d\xed\x1d\x9d\x5d\xdd\x3d\xbd\x7d\xfd\x03\x83\x43\xc3\x23\xa3\x63\xe3\x13\x93\x53\xd3\x33\xb3\x73\xf3\x0b\x8b\x4b\xcb\x2b\xab\x6b\xeb\x1b\x9b\x5b\xdb\x3b\xbb\x7b\xfb\x07\x87\x47\xc7\x27\xa7\x67\xe7\x17\x97\x57\xd7\x37\xb7\x77\xf7\x0f\x8f\x4f\xcf\x2f\xaf\x6f\xef\x1f\x9f\x5f\xdf\x3f\xbf\x7f/r; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment