This repository was archived by the owner on Oct 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrc.cpp
89 lines (74 loc) · 1.58 KB
/
crc.cpp
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <boost/crc.hpp>
void
usage()
{
fprintf(stderr, "Usage: crctool [-k] filename\n");
exit(1);
}
int
main(int argc, char * const*argv)
{
struct stat fstat;
FILE *foo;
void *data;
uint32_t result;
int ret;
bool write = false;
ret = getopt(argc, argv, "w");
if (ret == '?')
usage();
else if (ret == 'w')
write = true;
if (optind != argc - 1)
usage();
ret = stat(argv[optind], &fstat);
if (ret < 0) {
fprintf(stderr, "Could not stat %s", argv[optind]);
perror("");
exit(1);
}
foo = fopen(argv[optind], "r+b");
if (foo == NULL) {
perror("Could not open input file");
exit(1);
}
data = malloc(fstat.st_size);
if (data == NULL) {
fprintf(stderr, "OOM\n");
exit(1);
}
if (fread(data, fstat.st_size, 1, foo) != 1) {
fprintf(stderr, "Could not read whole input file\n");
exit(1);
}
// Flip all 32 bit words. Really.
{
uint32_t *ptr = (uint32_t*)data;
unsigned long count = fstat.st_size / 4;
assert((fstat.st_size % 4) == 0);
for (unsigned long i = 0; i < count; i++)
// XXX: baked in assumption that this'll actually swap
// bytes around.
ptr[i] = htonl(ptr[i]);
}
boost::crc_basic<32> crc32(0x04C11DB7, 0xFFFFFFFF, 0, false, false);
crc32.process_bytes(data, fstat.st_size);
result = crc32.checksum();
free(data);
if (write) {
fseek(foo, 8, SEEK_SET);
fwrite(&result, sizeof(result), 1, foo);
} else {
printf("%X\n", result);
}
fclose(foo);
return 0;
}