crc32 user program
This commit is contained in:
parent
0c765a412b
commit
d1efbdf3bd
2 changed files with 65 additions and 0 deletions
1
Makefile
1
Makefile
|
@ -138,6 +138,7 @@ UPROGS=\
|
|||
$U/_clear\
|
||||
$U/_halt\
|
||||
$U/_reset\
|
||||
$U/_crc32\
|
||||
$U/_traced\
|
||||
|
||||
fs.img: mkfs/mkfs README.md $(UPROGS)
|
||||
|
|
64
user/crc32.c
Normal file
64
user/crc32.c
Normal file
|
@ -0,0 +1,64 @@
|
|||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include "user.h"
|
||||
|
||||
uint32_t
|
||||
crc32_for_byte(uint32_t r)
|
||||
{
|
||||
for(int j = 0; j < 8; ++j)
|
||||
r = (r & 1 ? 0xEDB88320L ^ (r >> 1) : r >> 1);
|
||||
return r;
|
||||
}
|
||||
|
||||
void
|
||||
init_crc32_table(uint32_t table[256])
|
||||
{
|
||||
for(int i = 0; i < 256; ++i)
|
||||
table[i] = crc32_for_byte(i);
|
||||
}
|
||||
|
||||
uint32_t
|
||||
crc32(uint8_t *data, size_t len, uint32_t crc, uint32_t table[256])
|
||||
{
|
||||
for(size_t i = 0; i < len; ++i)
|
||||
crc = table[(crc ^ data[i]) & 0xFF] ^ (crc >> 8);
|
||||
return crc;
|
||||
}
|
||||
|
||||
int
|
||||
main(int argc, char *argv[])
|
||||
{
|
||||
int fd;
|
||||
uint8_t buf[1024];
|
||||
size_t n;
|
||||
uint32_t crc = 0xFFFFFFFF;
|
||||
uint32_t table[256];
|
||||
|
||||
if(argc != 2) {
|
||||
fprintf(stderr, "Usage: %s <file>\n", argv[0]);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if((fd = open(argv[1], 0)) < 0) {
|
||||
fprintf(stderr, "Couldnt open: %s\n", argv[1]);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
init_crc32_table(table);
|
||||
|
||||
while((n = read(fd, buf, sizeof(buf))) > 0)
|
||||
crc = crc32(buf, n, crc, table);
|
||||
|
||||
if(n < 0) {
|
||||
fprintf(stderr, "Couldnt read file...\n");
|
||||
close(fd);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
close(fd);
|
||||
|
||||
crc ^= 0xFFFFFFFF;
|
||||
printf("%x\n", crc);
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Add table
Reference in a new issue