提问人:vengy 提问时间:10/11/2023 最后编辑:vengy 更新时间:10/11/2023 访问量:108
自定义校验和算法
Custom Checksum Algorithm
问:
最近将一些旧的 MASM 校验和代码移植到 C 中。
MASM 代码用于计算缓冲区或文件的校验和。
我很好奇它类似于什么算法?
下面是 C 语言中正确的等效逻辑: 演示
#include <stdio.h>
#include <stdint.h>
uint32_t computeChecksum(uint8_t *data, size_t dataLength) {
uint32_t checksum = 0;
int rotateBits = 0;
for (size_t i = 0; i < dataLength; i += 4) {
// Process data in 32-bit chunks.
uint32_t chunk = *(uint32_t*)(data + i);
// Perform the ROL operation.
chunk = (chunk << rotateBits) | (chunk >> (32 - rotateBits));
// XORs the rotated chunk with a running checksum.
checksum ^= chunk;
// The number of bit positions the data is rotated increases by 1
// for each subsequent chunk and wraps around after 32.
rotateBits = (rotateBits + 1) % 32;
}
return checksum;
}
int main() {
uint8_t data[32] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10,
0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20
};
uint32_t checksum = computeChecksum(data, sizeof(data));
printf("Checksum: 0x%08X\n", checksum);
return 0;
}
答: 暂无答案
评论
dataLength