MurmurOAAT32 Hash Function and Tree Hashing
This code snippet includes a MurmurOAAT32 hash function and functions to convert an unsigned int to string, merge and hash two values, and recursively print hash values from a binary tree.unknown
c_cpp
10 months ago
2.1 kB
4
Indexable
#include <stdio.h> #include <stdlib.h> #include <string.h> // MurmurOAAT32 hash function unsigned int MurmurOAAT32(char *key) { unsigned int h = 3323198485u; for (; *key; ++key) { h ^= *key; h *= 0x5bd1e995; h ^= h >> 15; } return h; } // Function to convert unsigned int to string void unsigned_int_to_string(unsigned int num, char *str) { sprintf(str, "%u", num); } // Function to merge and hash two values in the binary tree unsigned int merge_and_hash(unsigned int a, unsigned int b) { unsigned int sum = a + b; char buffer[11]; // enough to hold a 32-bit unsigned int unsigned_int_to_string(sum, buffer); return MurmurOAAT32(buffer); } // Recursive function to print hash values from root to leaves void print_hashes(unsigned int *hashes, int n) { if (n == 1) { printf("%-15u\n", hashes[0]); return; } int new_n = (n + 1) / 2; unsigned int *new_hashes = (unsigned int *)malloc(new_n * sizeof(unsigned int)); for (int i = 0; i < new_n; i++) { if (2 * i + 1 < n) { new_hashes[i] = merge_and_hash(hashes[2 * i], hashes[2 * i + 1]); } else { char buffer[11]; unsigned_int_to_string(hashes[2 * i] * 2, buffer); new_hashes[i] = MurmurOAAT32(buffer); } } print_hashes(new_hashes, new_n); for (int i = 0; i < n; i++) { printf("%-15u", hashes[i]); } printf("\n"); free(new_hashes); } int main() { int n; //printf("Enter the number of strings: "); scanf("%d", &n); char **strings = (char **)malloc(n * sizeof(char *)); unsigned int *hashes = (unsigned int *)malloc(n * sizeof(unsigned int)); //printf("Enter the strings:\n"); for (int i = 0; i < n; i++) { strings[i] = (char *)malloc(101 * sizeof(char)); // 100 chars + null terminator scanf("%s", strings[i]); hashes[i] = MurmurOAAT32(strings[i]); } print_hashes(hashes, n); for (int i = 0; i < n; i++) { free(strings[i]); } free(strings); free(hashes); return 0; }
Editor is loading...
Leave a Comment