1 2 3 4 5 6 7
my $data = "123456789"; use Digest::CRC qw(crc); # name, [width, init, xorout, refout, poly, refin, cont); # crc8 => [8, 0, 0, 0, 0x07, 0, 0], # deins => [8, 0xFF, 0, 0, 0x2F, 0, 0] my $crc = crc($data,8,0xff,0,0,0x2F,0,0);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
use strict; use warnings; my ($poly, $crc8_initval, $crc8, $i, $j, $fbit, $bitcnt, $data); my @crc8_table; $poly = 0x2F; # => x^8 + x^5 + x^3 + x^2 + X + 1 $crc8_initval = 0xFF; @crc8_table = (); for ($i=0; $i<256; $i++) { $data = $i; $crc8 = $crc8_initval; for($bitcnt = 8; $bitcnt>0; $bitcnt--) { $fbit = ($crc8 ^ $data) & 0x01; if ($fbit == 1) { $crc8 = $crc8 ^ $poly; } $crc8 = ($crc8>>1) & 0x7F; if ($fbit == 1) { $crc8 = $crc8 | 0x80; } $data = $data>>1; } #printf("crc8[$i] = $crc8\n"); $crc8_table[$i] = $crc8; } #print table as c code: printf("\n\n"); printf("unsigned char crc8_lookuptable[256] = {"); for($i=0; $i<256; $i+=16) { printf("\n"); for($j=0; $j<16; $j++) { printf(" 0x%02X,",$crc8_table[$i+$j]); } } printf("\n};\n\n");
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
######## Quelle: http://www.miscel.dk/MiscEl/CRCcalculations.html#CRC8 ##### use strict; use warnings; use 5.010; ## CRC8 bit sub Crc8 { my $Buffer = shift; my $Poly = shift; my $Init = shift; my @Buffer = split //,$Buffer; my $Result = $Init; for my $i (1..length($Buffer)) { $Result = $Result ^ ord($Buffer[$i-1]); for my $j (0..7) { $Result = ($Result & 0x80) ? ($Result << 1) ^ $Poly : $Result << 1; } } $Result = $Result & 0xFF; return $Result; } ### CRC8 byte, normal my @CrcTable = (); sub GenerateTableCrc8 { my $Poly = shift; for my $i (0..255) { $CrcTable[$i]= Crc8(chr($i),$Poly,0); } } sub Crc8Byte { my $Buffer = shift; my $Initial = shift; my $Result = $Initial; my @Buffer = split //,$Buffer; for my $i(1..length($Buffer)){ $Result = ($Result << 8) ^ $CrcTable[ (ord($Buffer[$i-1]) ^ ($Result)) & 0xFF ]; } $Result = $Result & 0xFF; return $Result; }
1 2 3 4
GenerateTableCrc8(0x2F); my $daten = 'Dead cows dont make Mooooo!'; my $crc = Crc8Byte($daten,0xFF); print $crc;