General Information
Tutorials
Reference Manuals
Libraries
Translation Tasks
Tools
Administration
|
Solutions of common problemsComputing a Hash ValueThis C module computes a 32-bit hash of the contents of specified memory. Every bit of the memory contents affects every bit of the hash. The probability that the same hash will be computed for different memory contents is very low. The module is instantiated by $/Tech/Hash.specs
All entities exported by this module can be used in specifications
of type The module exports the following entities:
In the simplest case, we need to compute a hash for the contents of a single contiguous block of memory. For example, here is a call to compute a hash of a single string pointed to by `str':
hash(str, strlen(str), 0) A more complex situation is when there are several related areas of memory, and we need to compute a single hash for all of them. Suppose that there was a pair of strings, pointed to by `str1' and `str2', which constituted a conceptual unit. Here are two ways to compute a single hash for the pair:
hash(str1, strlen(str1), hash(str2, strlen(str2), 0)) hash(str2, strlen(str2), hash(str1, strlen(str1), 0))Either of these sequences would be perfectly satisfactory, but the resulting values would differ. When computing the hash of an array or structure, it is important to realize that there may be padding with unknown content involved. Consider the following variable declaration:
struct{ char c; int i; } foo, bar;On some machines, the compiler may insert three bytes of padding between the end of field `c' and the beginning of field `i'. There is no guarantee that these three bytes will be initialized in a particular way. Thus `hash(foo, sizeof(foo), 0)' and `hash(bar, sizeof(bar), 0)' may not yield the same result when `foo' and `bar' have identical field values; the hash also depends on the contents of the padding. Unless you know that there is no padding present, or that padding is always intialized in the same way, the only safe approach is to hash the fields as separate memory areas:
hash (foo.c, sizeof(foo.c), hash(foo.i, sizeof(foo.i), 0))
|