cynix

x86 UNIX-like OS
git clone git://git.2f30.org/cynix
Log | Files | Refs | README | LICENSE

hash.c (767B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <sys/types.h>
      4 #include <sys/stat.h>
      5 #include <fcntl.h>
      6 #include <stdint.h>
      7 #include <string.h>
      8 
      9 uint32_t
     10 get_fnv_hash(const char *buf, size_t count, uint32_t hash)
     11 {
     12 	static uint32_t fnv_offset_basis = 2166136261;
     13 	static uint32_t fnv_prime = 16777619;
     14 
     15 	hash = (!hash) ? fnv_offset_basis : hash;
     16 	while (count--) {
     17 		hash ^= *buf++;
     18 		hash *= fnv_prime;
     19 	}
     20 
     21 	return hash;
     22 }
     23 
     24 int
     25 main(void)
     26 {
     27 	int fd;
     28 	char buf[256];
     29 	ssize_t ret;
     30 	uint32_t hash = 0;
     31 
     32 	fd = open("big", O_RDONLY);
     33 	if (fd < 0)
     34 		return EXIT_FAILURE;
     35 	do {
     36 		ret = read(fd, buf, 255);
     37 		if (ret <= 0) break;
     38 		buf[ret] = '\0';
     39 		hash = get_fnv_hash(buf, ret, hash);
     40 	} while (1);
     41 	printf("hash = 0x%08lx\n", hash);
     42 	close(fd);
     43 	return EXIT_SUCCESS;
     44 }
     45