added crc32

This commit is contained in:
aiju 2014-09-30 13:07:36 +02:00
parent 4f4d71b941
commit 4f264cedfb
3 changed files with 102 additions and 2 deletions

99
sys/src/cmd/crc32.c Normal file
View file

@ -0,0 +1,99 @@
#include <u.h>
#include <libc.h>
#include <libsec.h>
u32int table[256];
u32int xor = -1, init, poly = 0xedb88320;
char *error;
static void
dotable(void)
{
u32int c;
int n, k;
for(n = 0; n < 256; n++){
c = n;
for(k = 0; k < 8; k++)
if((c & 1) != 0)
c = poly ^ c >> 1;
else
c >>= 1;
table[n] = c;
}
}
static u32int
calc(u32int init, uchar *buf, ulong len)
{
u32int c;
c = init;
while(len-- != 0)
c = table[(*buf++ ^ c) & 0xff] ^ c >> 8;
return c;
}
static void
sum(int fd, char *name)
{
int n;
uchar buf[8192];
u32int crc;
crc = init ^ xor;
while((n = read(fd, buf, sizeof buf)) > 0)
crc = calc(crc, buf, n);
if(n < 0){
fprint(2, "reading %s: %r\n", name ? name : "stdin");
error = "read";
return;
}
crc ^= xor;
if(name == nil)
print("%ux\n", crc);
else
print("%ux\t%s\n", crc, name);
}
void
usage(void)
{
fprint(2, "usage: %s [-x xorval] [-i initial] [-p poly] [file...]\n", argv0);
exits("usage");
}
void
main(int argc, char *argv[])
{
int i, fd;
ARGBEGIN{
case 'x':
xor = strtol(EARGF(usage()), 0, 0);
break;
case 'i':
init = strtol(EARGF(usage()), 0, 0);
break;
case 'p':
poly = strtol(EARGF(usage()), 0, 0);
break;
default:
usage();
}ARGEND
dotable();
if(argc == 0)
sum(0, nil);
else for(i = 0; i < argc; i++){
fd = open(argv[i], OREAD);
if(fd < 0){
fprint(2, "crc32: can't open %s: %r\n", argv[i]);
error = "open";
continue;
}
sum(fd, argv[i]);
close(fd);
}
exits(error);
}

View file

@ -198,8 +198,8 @@ loadrom(char *file)
if(fd < 0)
sysfatal("open: %r");
sz = seek(fd, 0, 2);
if(sz <= 0 || sz >= 32*1024*1024)
sysfatal("nope.jpg");
if(sz <= 0 || sz > 32*1024*1024)
sysfatal("invalid file size");
seek(fd, 0, 0);
nrom = sz;
rom = emalloc(nrom);

View file

@ -95,6 +95,7 @@ loadbat(char *file)
char *s;
if(battery && nsram != 0){
buf[sizeof buf - 1] = 0;
strncpy(buf, file, sizeof buf - 5);
s = buf + strlen(buf) - 4;
if(s < buf || strcmp(s, ".smc") != 0)