rp2040

RP2040 Programming without SDK
Log | Files | Refs

bincrc.c (1517B)


      1 #include <stdio.h>
      2 #include <stdint.h>
      3 
      4 uint32_t
      5 crc32(uint8_t *idata, size_t len)
      6 {
      7 	uint32_t pol = 0x04C11DB7;
      8 	uint32_t c   = 0xFFFFFFFF;
      9 	uint32_t b;
     10 
     11 	for (int i = 0; i < len; i++) {
     12 		b = idata[i] << 24;
     13 		c ^= b;
     14 		for (int j = 0; j < 8; j++) {
     15 			c = c >> 31 & 1 ? c << 1 ^ pol : c << 1;
     16 		}
     17 	}
     18 
     19 	return c;
     20 }
     21 
     22 int
     23 main(int argc, char *argv[])
     24 {
     25 	FILE *src, *dst;
     26 	size_t isize, osize = 256;
     27 	uint8_t idata[osize];
     28 	uint32_t cs;
     29 	int ret = 0;
     30 
     31 	if (argc != 3) {
     32 		fprintf(stderr, "Usage: %s src dst\n", argv[0]);
     33 		ret = 1;
     34 		goto defer;;
     35 	}
     36 
     37 	if ((src = fopen(argv[1], "r")) == NULL) {
     38 		fprintf(stderr, "Could not open %s.\n", argv[1]);
     39 		ret = 1;
     40 		goto defer;;
     41 	}
     42 
     43 	if ((dst = fopen(argv[2], "w")) == NULL) {
     44 		fprintf(stderr, "Could not open %s.\n", argv[2]);
     45 		ret = 1;
     46 		goto defer;;
     47 	}
     48 
     49 	if ((isize = fread(idata, 1, osize, src)) < 0) {
     50 		fprintf(stderr, "Read error.\n", argv[2]);
     51 		ret = 1;
     52 		goto defer;
     53 	}
     54 	for (int i = isize; i < osize - 4; i++)
     55 		idata[i] = 0;
     56 
     57 	cs = crc32(idata, osize - 4);
     58 	for (int i = 0; i < 4; i++)
     59 		idata[osize - 4 + i] = cs >> i * 8;
     60 
     61 	if (fwrite(idata, 1, osize, dst) != osize) {
     62 		fprintf(stderr, "Write error.\n");
     63 		ret = 1;
     64 		goto defer;;
     65 	}
     66 
     67 	while ((isize = fread(idata, 1, osize, src)) > 0)
     68 		if (fwrite(idata, 1, isize, dst) < isize) {
     69 			fprintf(stderr, "Write error.\n");
     70 			ret = 1;
     71 			goto defer;;
     72 		}
     73 
     74 	if (isize < 0) {
     75 		fprintf(stderr, "IO error.\n");
     76 		ret = 1;
     77 		goto defer;;
     78 	}
     79 
     80 defer:
     81 	if (src)
     82 		fclose(src);
     83 	if (dst)
     84 		fclose(dst);
     85 	return ret;
     86 }