最近有对文件添加CRC的需要,简单写了一个python脚本处理

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
# -*- coding:utf-8 -*-
import binascii
import hashlib
import os
import sys
import shutil


def crc2hex_LSB(crc):
res=''
for i in range(4):
t=crc & 0xFF
crc >>= 8
res='%s%02X' % (res, t)
return res

while True:
while True:
file = input("\n输入文件路径:")
if (not os.path.isfile(file)):
print("不是一个文件!")
else:
break
file_path = os.path.splitext(file)[0] #取路径+文件名(去除扩展名)

fd = open(file, "rb")
crc_pre = binascii.crc32(fd.read(os.path.getsize(file)-4))
# print(hex(crc_pre))
crc_end = int.from_bytes(fd.read(),"little")
# print(hex(crc_end))
fd.close()


if crc_pre == crc_end:
ack = input("似乎已有CRC校验码,是否继续添加? y继续:")
if not(ack=="y" or ack=="Y"):
print('取消操作')
continue
file2 = file_path + "_CRC.bin"
shutil.copy2(file,file2)
fd2 = open(file2, "r+b")

crc = binascii.crc32(fd2.read())
recrc = crc2hex_LSB(crc)
r=binascii.unhexlify(recrc)

fd2.write(r)

fd2.seek(0, 0)
md5 = hashlib.md5(fd2.read()).hexdigest().upper()
fd2.close()
print('\n生成成功:',os.path.basename(file2))
print('CRC32\t:', hex(crc))
print('MD5\t:',md5)

再补一个C版本的

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
#include <stdio.h>
#include <stdlib.h>

static unsigned int crc32_byte(unsigned char data, unsigned int crc)
{
for (unsigned char i = 0; i < 8; i++)
{
if (((crc ^ data) & 1) != 0)
{
crc = ((crc >> 1) & 0x7FFFFFFF) ^ 0xEDB88320;
}
else
{
crc = (crc >> 1) & 0x7FFFFFFF;
}

data = (data >> 1) & 0x7FFFFFFF;
}

return crc;
}


static unsigned int crc32(FILE *file)
{
unsigned int data = 0;
unsigned int crc = 0xFFFFFFFF;
unsigned char byte;

while (fread(&byte, 1, 1, file) == 1)
{
data = byte & 0xff;
crc = crc32_byte(data, crc);
}

return crc ^ 0xFFFFFFFF;
}

static void append_crc32(FILE *file, unsigned int crc)
{
unsigned char bytes[4];
bytes[3] = (crc >> 24) & 0xFF;
bytes[2] = (crc >> 16) & 0xFF;
bytes[1] = (crc >> 8) & 0xFF;
bytes[0] = crc & 0xFF;
fwrite(bytes, 1, 4, file);
}

int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: %s filename\r\n", argv[0]);
return 1;
}

char *filename = argv[1];
FILE *file = fopen(filename, "rb+");

if (file == NULL)
{
perror("Error opening file\r\n");
return 2;
}

unsigned int crc = crc32(file);
append_crc32(file, crc);
fclose(file);

printf("--------------------------------------\r\n");
printf("CRC32 of %s is [0x%08X]\r\n", filename, crc);
printf("--------------------------------------\r\n");
return 0;
}