Wie man das STM32H7-Hardware-CRC konfiguriert, um mit zlib CRC32 in Python übereinzustimmen
Sie können die STM32-CRC32-Peripherie so konfigurieren, dass sie mit dem CRC32-Algorithmus übereinstimmt, der von zlib verwendet wird (welcher im zlib-Modul von Python verfügbar ist):
Laut crccalc.com verwendet zlib CRC32 (dort CRC-32/ISO-HDLC genannt) Init=0xFFFFFFFF, XorOut=0xFFFFFFFF und byte-weise Umkehrung von Eingabe & Ausgabe.
Auf dem STM32H7 können Sie die HAL verwenden, um die CRC-Peripherie entsprechend zu konfigurieren:
crc_example.cpp
void Init_CRC32() {
__HAL_RCC_CRC_CLK_ENABLE();
// Reset CRC
_hcrc.Instance = CRC;
_hcrc.Init.DefaultPolynomialUse = DEFAULT_POLYNOMIAL_ENABLE;
_hcrc.Init.DefaultInitValueUse = DEFAULT_INIT_VALUE_ENABLE;
_hcrc.Init.InputDataInversionMode = CRC_INPUTDATA_INVERSION_BYTE;
_hcrc.Init.OutputDataInversionMode = CRC_OUTPUTDATA_INVERSION_ENABLE;
_hcrc.InputDataFormat = CRC_INPUTDATA_FORMAT_BYTES;
HAL_CRC_Init(&_hcrc);
}
uint32_t CalculateCRC32(void* data, size_t length)
{
// Compute the CRC
uint32_t crc_result = HAL_CRC_Calculate(&_hcrc, reinterpret_cast<uint32_t*>(data), length);
// Invert to obtain ZLIB CRC32
return crc_result ^ 0xFFFFFFFF;
}Der folgende Testcode kann verwendet werden, um das Ergebnis zu validieren
crc_test.cpp
void TestCRC32() {
uint32_t crc = CalculateCRC32((void*)"DEADBEEF", 8);
printf("CRC32 of 'DEADBEEF': %08X", crc);
// When testing, always include a non-divisible-by-4 number of bytes
crc = CalculateCRC32((void*)"Hello, World!", 13);
SendLogMessageF("CRC32 of 'Hello, World!': %08X", crc);
}Ausgabe:
crc_test_output.txt
CRC32 of 'DEADBEEF': E24CEE98
CRC32 of 'Hello, World!': EC4AC3D0Äquivalenter Python-Code
Der Python-Code dafür ist extrem einfach, da er das eingebaute zlib-Modul verwendet:
zlib_crc32.py
import zlib
def calculate_crc32(data: bytes) -> int:
return zlib.crc32(data)
print(f"CRC32 of 'Hello, World!': {calculate_crc32(b'Hello, World!'):08X}")
print(f"CRC32 of 'DEADBEEF': {calculate_crc32(b'DEADBEEF'):08X}")Ausgabe:
zlib_crc32_output.txt
CRC32 of 'DEADBEEF': E24CEE98
CRC32 of 'Hello, World!': EC4AC3D0Sie können es sogar inline machen:
zlib_crc32_inline.py
import zlib
print(f'{zlib.crc32(b"DEADBEEF"):08X}') # E24CEE98If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow