]> www.fi.muni.cz Git - slotcarman.git/blob - SCX/CRC.pm
Proof-of-concept implementation.
[slotcarman.git] / SCX / CRC.pm
1 #!/usr/bin/perl -w
2
3 use strict;
4
5 package SCX::CRC;
6
7 our @crctable;
8
9 sub import {
10         return if @crctable;
11
12         my @table = (0x31);
13
14         for my $i (1..7) {
15                 my $n = 2 * $table[-1];
16                 push @table, $n > 0xff ? ($n ^ 0x31) & 0xff: $n;
17         }
18
19         @crctable = (0x00);
20
21 #       print "Table = ", join(' ', map { sprintf("%02x", $_) } @table), "\n";
22
23         for my $i (0x01 .. 0xff) {
24                 $crctable[$i] ^= $table[0] if $i & 0x01;
25                 $crctable[$i] ^= $table[1] if $i & 0x02;
26                 $crctable[$i] ^= $table[2] if $i & 0x04;
27                 $crctable[$i] ^= $table[3] if $i & 0x08;
28                 $crctable[$i] ^= $table[4] if $i & 0x10;
29                 $crctable[$i] ^= $table[5] if $i & 0x20;
30                 $crctable[$i] ^= $table[6] if $i & 0x40;
31                 $crctable[$i] ^= $table[7] if $i & 0x80;
32         }
33
34 #       print "CRCtable = ", join(' ', map { sprintf("%02x", $_) } @crctable), "\n";
35 }
36
37 sub digest_str {
38         my ($str) = @_;
39
40         return digest(unpack("C*", $str));
41
42 }
43
44 sub digest {
45         my (@bytes) = @_;
46
47         my $res = 0;
48
49         for my $byte (@bytes) {
50                 my $idx = $byte ^ $res;
51                 $res = $crctable[$idx];
52         }
53
54         return $res ^ 0xbb;
55 }
56
57 1;
58