yincheng.zhong
2 天以前 567085ead3f6adaabd884f16ab4b17c62e8f0403
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
import struct
import binascii
 
# 下载文件
with open('test_data.bin', 'rb') as f:
    data = f.read()
 
print(f"Total size: {len(data)} bytes")
print(f"First 16 bytes: {data[:16].hex()}")
 
# 数据部分(不包括最后4字节CRC)
data_only = data[:-4]
crc_stored = struct.unpack('<I', data[-4:])[0]
 
print(f"\nStored CRC32: 0x{crc_stored:08X}")
print(f"Data size: {len(data_only)} bytes")
 
# 标准CRC32(按字节流)
crc_standard = binascii.crc32(data_only, 0) & 0xFFFFFFFF
print(f"\n1. Standard CRC32 (byte stream, init=0): 0x{crc_standard:08X}")
 
# 模拟STM32 Word模式(32位小端)
# 将数据按4字节分组,每组作为32位小端整数
def crc32_word_mode_le(data):
    """模拟STM32 Word模式,小端字节序"""
    crc = 0
    offset = 0
    
    # 处理完整的4字节块
    while offset + 4 <= len(data):
        word = struct.unpack('<I', data[offset:offset+4])[0]  # 小端读取
        word_bytes = struct.pack('<I', word)  # 再转回字节
        crc = binascii.crc32(word_bytes, crc) & 0xFFFFFFFF
        offset += 4
    
    # 处理剩余字节(补零对齐)
    if offset < len(data):
        remaining = data[offset:]
        word_bytes = remaining + b'\x00' * (4 - len(remaining))
        crc = binascii.crc32(word_bytes, crc) & 0xFFFFFFFF
    
    return crc
 
crc_word_le = crc32_word_mode_le(data_only)
print(f"2. Word mode (little-endian, init=0):    0x{crc_word_le:08X}")
 
# 模拟STM32 Word模式(32位大端)
def crc32_word_mode_be(data):
    """模拟STM32 Word模式,大端字节序"""
    crc = 0
    offset = 0
    
    # 处理完整的4字节块
    while offset + 4 <= len(data):
        word = struct.unpack('>I', data[offset:offset+4])[0]  # 大端读取
        word_bytes = struct.pack('>I', word)  # 再转回字节
        crc = binascii.crc32(word_bytes, crc) & 0xFFFFFFFF
        offset += 4
    
    # 处理剩余字节(补零对齐)
    if offset < len(data):
        remaining = data[offset:]
        word_bytes = remaining + b'\x00' * (4 - len(remaining))
        crc = binascii.crc32(word_bytes, crc) & 0xFFFFFFFF
    
    return crc
 
crc_word_be = crc32_word_mode_be(data_only)
print(f"3. Word mode (big-endian, init=0):       0x{crc_word_be:08X}")
 
# 检查匹配
print(f"\n{'✓ MATCH!' if crc_standard == crc_stored else '✗ No match'} - Standard")
print(f"{'✓ MATCH!' if crc_word_le == crc_stored else '✗ No match'} - Word LE")
print(f"{'✓ MATCH!' if crc_word_be == crc_stored else '✗ No match'} - Word BE")