--- guess-crc.pl 2008/09/28 22:17:22 11 +++ guess-crc.pl 2008/09/29 16:28:49 12 @@ -9,13 +9,37 @@ use Digest::CRC qw(crc32 crc16 crcccitt crc crc8); use Data::Dump qw/dump/; +my $debug = 1 if @ARGV; + sub hex2b { my $hex = shift; return map { hex($_) } split(/\s+/, $hex); } -my @poly; -# ( 32833, 43271, 32833, 43271, 19299, 35925, 47123, 49319, 56971 ); +my @check_polys = ( 0x0000 .. 0xffff ); +@check_polys = ( 32833, 43271, 32833, 43271, 19299, 35925, 47123, 49319, 56971 ); + +my @check_offset = ( 0,1,2,3 ); +@check_offset = ( 1 ); # skip first, second always zero + +my $found_polys; + +sub check_crc { + my ( $poly, $bytes, $wanted ) = @_; + my $ctx = Digest::CRC->new( + #width=>16, init=>0xffff, xorout=>0, refout=>1, poly=>0x1021, refin=>0 # ccitt + #width=>16, init=>0, xorout=>0, refout=>1, poly=>0x8005, refin=>1 # crc16 + #0x8408, + #0xa001, + width=>16, init=>0, xorout=>0, refout=>1, poly=>$poly,refin=>1 + #width=>16, init=>0xffff, xorout=>0, refout=>1, poly=>$poly, refin=>0 # ccitt + ); + $ctx->add( $bytes ); + my $try = $ctx->digest; + my $str = pack('n*', $try); + warn "## check_crc( $poly, ",dump($bytes)," ) = ",dump( $str, $wanted ) if $debug; + return $str eq $wanted; +} foreach ( 'D5 00 05 04 00 11 8C 66', @@ -26,37 +50,24 @@ my $bytes = pack('H*', substr($hex, 0, -4)); - warn "?? crc ",substr($hex,-4); + warn "?? guess crc ",substr($hex,-4); my $crc = pack('H4', substr($hex,-4)); warn "input $_ => ",dump( $bytes, $crc ); - foreach my $o ( 0,1,2,3 ) { + foreach my $o ( @check_offset ) { my $b = substr( $bytes, $o ); - foreach my $poly ( 0x0000 .. 0xffff ) { + foreach my $poly ( @check_polys ) { print "## poly $poly\n" if $poly % 1000 == 0; - my $ctx = Digest::CRC->new( - #width=>16, init=>0xffff, xorout=>0, refout=>1, poly=>0x1021, refin=>0 # ccitt - #width=>16, init=>0, xorout=>0, refout=>1, poly=>0x8005, refin=>1 # crc16 - #0x8408, - #0xa001, - width=>16, init=>0, xorout=>0, refout=>1, poly=>$poly,refin=>1 - ); - $ctx->add( $b ); - my $try = $ctx->digest; - - my $v = pack('v*', $try); - my $n = pack('n*', $try); - - if ( $v eq $crc or $n eq $crc ) { - warn "HIT: $o poly: $poly ",dump( $crc, $v, $n ); - push @poly, $poly; + if ( check_crc( $poly, $b, $crc ) ) { + warn "HIT: $o poly: $poly\n"; + $found_polys->{$poly}->{$o}++; } } } } -print "FOUND poly = ", dump( @poly ); +print "FOUND polys = ", dump( $found_polys );