perl语言有次强大的正则表达式功能,因而我喜欢使用perl语言进行一些数据分析,在项目中也需要生成文件的crc值,在网上很多都是引用第三方的库进行计算,crc计算是使用位计算得来,因此可以通过纯perl计算crc值,本函数来源于网上某位大侠,经测试计算正确,以下是代码:
#文件名:test.pl
#执行:@perl.exe test.pl
#计算crc32
#使用方法 makecrc32(string,string,string,crcvalue);
sub makecrc32
{
my ($input, $init_value, $polynomial) = @_;
$init_value = 0 unless (defined $init_value);
$polynomial = 0xedb88320 unless (defined $polynomial);
my @lookup_table;
for (my $i=0; $i<256; $i++) {
my $x = $i;
for (my $j=0; $j<8; KaTeX parse error: Expected '}', got 'EOF' at end of input: …++) {
if (x & 1) {
x=(x = (x=(x >> 1) ^ $polynomial;
} else {
$x = $x >> 1;
}
}
push @lookup_table, $x;
}
my $crc = $init_value ^ 0xffffffff;
foreach my $x (unpack (‘C*’, $input)) {
crc=((crc = ((crc=((crc >> 8) & 0xffffff) ^ lookuptable[(lookup_table[ (lookuptable[(crc ^ $x) & 0xff ];
}
$crc = $crc ^ 0xffffffff;
return $crc;
}
#打开文件计算crc值
sub test
{
my outfile="test.dat";open(outfile = "test.dat";
open(outfile="test.dat";open(binoutfilehandl,"+>outfile")∣∣die"Errorinopeningoutputfile>outfile")|| die "Error in opening outputfile >outfile")∣∣die"Errorinopeningoutputfile>outfile\n";
binmode($binoutfilehandl);
#计算crc32
my $crcvalue=0;
my bufferlen=255;seek(bufferlen = 255;
seek(bufferlen=255;seek(binoutfilehandl,0,0); #定位到文件头
my $readbuffer = “”;
my $readdatalen = 0;
do
{
$readbuffer = “”;
readdatalen=read(readdatalen = read(readdatalen=read(binoutfilehandl, $readbuffer, KaTeX parse error: Expected 'EOF', got '#' at position 13: bufferlen); #̲读取文件
#outVar = unpack(“H*”, readbuffer);printf(readbuffer);
printf(readbuffer);printf(logfilehandl “read data len: %d\n”,readdatalen);if(readdatalen);
if(readdatalen);if(readdatalen>0)
{
crcvalue=makecrc32(crcvalue=makecrc32(crcvalue=makecrc32(readbuffer,KaTeX parse error: Expected 'EOF', got '}' at position 14: crcvalue);
}̲
}
while(readdatalen>0);
strtemp=sprintf("crc:strtemp = sprintf("crc:%x",strtemp=sprintf("crc:crcvalue);
strdata=uc(strdata = uc(strdata=uc(strtemp); #转为大写
seek(KaTeX parse error: Expected 'EOF', got '#' at position 23: …ilehandl,0,2); #̲定位到文件尾
print…strdata);
close($binoutfilehandl);
}