作者: Jim Wang 公众号: 巴博萨船长
摘要:本文讨论如何使用Perl语言实现CRC-16算法和应用
Abstract: This article discusses how to use Perl language to implement CRC-16 algorithm and application
作者: Jim Wang 公众号: 巴博萨船长
代码
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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
|
my @table; sub generateCRC16() { my $i = 0; my @lst; my $data; my $crc; while ($i < 256) { $data = ($i<<1); $crc = 0; my $j = 8; while($j > 0) { $data >>=1; if (($data ^ $crc) & 0x0001) { $crc = ($crc >> 1) ^ 0xA001; } else { $crc >>= 1; } $j -= 1; } $lst[$i] = $crc; $i +=1; } return @lst; } @table = generateCRC16(); print "-----------------------------------------------\n"; print "The following is the crc-16 table:\n"; my $c = 1; for $a (@table) { printf ("0x%X",$a); print "\t"; if (($c % 8 == 0) & ($c != 0)) { print "\n"; } $c += 1; } print "-----------------------------------------------\n"; sub calculaterCRC() { my $string = shift(@_); my $crc = 0xFFFF; foreach $chr (unpack("C*", $string)) { $crc = ($crc >> 8) ^ $table[($crc ^ $chr) & 0xFF ]; } my $crcL = sprintf("\\x%X", &_Lo($crc)); my $crcH = sprintf("\\x%X", &_Hi($crc)); return $crcH.$crcL; }
sub convertchrtoacsii() { my $string = shift(@_); foreach $chr (unpack("C0U4", $string)) { print $chr." the acsii code is: ".ord($chr)." in hex format: "; printf "%X\n", (ord($chr)); } return; } sub _Lo() { my $myhex = shift(@_); return ($myhex & 0x00FF); } sub _Hi() { my $myhex = shift(@_); return (($myhex & 0xFF00) >> 8); } sub checkCrc() #用于检查CRC码时候匹配 { my ($payload, $crcsum) = @_; print $payload."---\n"; print $crcsum."+++\n"; if ($crcsum eq &calculaterCRC($payload)) { print "check CRC summe>>: not match!!\n"; return 1; } else { print "check CRC summe>>: match!!\n"; return 0; } } sub embedPayload # 此方法主要实现将字符串中的字符转换为十六进制,并加入:作为分隔符 { my $string = shift(@_); my @chrs = (unpack("(a)*", $string)); my @newchrs = map { sprintf("%X", (ord($_)))} @chrs; my $iterms =join (":", @newchrs); return $iterms; } sub extraPayload # 上述方法的逆操作 { my $iterms = shift(@_); my @chrs = split(":",$iterms); my @newchrs = map { chr(hex($_))} @chrs; my $string =join ("", @newchrs); return $string; } print "-----------------------------------------------\n"; print &embedPayload("ABCD")."\n"; print "---------\n"; print &extraPayload(&embedPayload("ABCD"));
|
先上代码,由于整理博客,代码分析以后整理添加。欢迎交流提意见彼此提高。需要声明一下51cto博客作者zuiwuxin就是作者本人,所以不存在版权问题。以后该博客将作为个人文章的主要发布地。