A C Program a Day

2019-10-09 - A simple hashing algorithm

Here's a program which computes a hash of the contents of stdin. I'm not entirely sure how good it is, but I've tested it a bit, and it seems to always produce different results.
(I decided to make this because right now, whenever I want to compile one of the C programs, I have to compile all of them, so this can be used to automatically determine which ones have to be re-compiled.)

Today's procedure is writes.


#include "procs-2019-10-09.c"

int main(void) {
	char buffer[256];
	unsigned long hash = 0;
	unsigned long r = 0;
	ssize_t bytesread;
	while ((bytesread = read(stdin, buffer, sizeof buffer)) > 0) {
		ssize_t i;
		for (i = 0; i < bytesread; i++) {
			hash += (unsigned long)buffer[i] * 0xf1ac3423;
			hash ^= 0xfacecab123;
			hash *= 0xf389c9832fc - r;
			r = (r * 0xf1c123124 + 0xeffee422 * (unsigned long)buffer[i]) >> 4;
	if (bytesread < 0) {
		writes(stderr, "Error reading from stdin.");
		return exitfailure;
	while (hash > LONG_MAX) hash -= LONG_MAX;
	writel(stdout, (long)hash);
	write(stdout, "\n", 1);
	return 0;

This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org/>