💾 Archived View for republic.circumlunar.space › users › grimmware › bbcresources › spi › crc_calc ›… captured on 2023-06-14 at 14:36:00.

View Raw

More Information

⬅️ Previous capture (2021-12-04)

-=-=-=-=-=-=-

#include <stdio.h>

unsigned int calculate_crc(FILE *fp) {
	unsigned int crc = 0;
	unsigned int length = 0;
	char byte;
	while(1) {
		fread(&byte, 1, 1, fp);
		if (feof(fp)) break;
		length += 1;
		crc ^=(byte << 8);
		for (int k=0; k<8; k++) {
			if (crc & 32768)
				crc=(((crc ^ 0x0810) & 32767) << 1)+1;
			else crc = crc << 1;
		}
	}
	return crc;
}

int main(int argc, char *argv[]){
	unsigned int crc = 0;
	if (argc != 2){
		fprintf(stderr, "Usage: %s FILENAME\n", argv[0]);
		return 1;
	}
	FILE *fp = fopen(argv[1], "r");
	crc = calculate_crc(fp);
	fclose(fp);
	if(crc == 0){
		fprintf(stderr, "Could not calculate CRC");
		return 1;
	}
	printf("CRC=%X", crc);
	return 0;
}