I have the following piece of code:
public void AddHash( int val )
{
m_Hash ^= (val & 0x3FFFFFF);
m_Hash ^= (val >> 26) & 0x3F;
}
I would like very much to know what the heck it does, but I would be satisfied to know how to build a bool HasHash( int val ) that tells me whether m_Hash has that number or not…
something like this?
public bool HasHash( int val )
{
return (m_Hash & val) == 0;
}
EDIT to fix the bug that @schnaader found: What it does? This code probably wants to rotate
valleftwards (clockwise) by 6 bits and form the ones-complement sum (edit: not the product, as I’d said before) — the xor — of that rotated value and the current value ofm_Hashto yield a newm_Hash. That newm_Hashwill be used the next timeAddHash( )is called.However, the code as written has a bug: it rotates only the high-order 6 bits of
valleftwards, leaving in place the low-order 26 bits ofval. The code then xors together three values:val;val; andm_Hashleaving the result in
m_Hash.How does it do it? You can just map it out and emulate it:
val & 0x3FFFFFFmeans extract the low-order 26 bits ofval.xorthose 26 bits with the current value ofm_Hashnow shift
valrightwards such that the low-order 26 bits drop off the low-order end, leaving what used to be the high-order 6 bits ofvalin the low-order 6 bits ofval.0x3fto extract only those low-order 6 bits (in case some extraneous bits got shifted into the high order part ofval).xorthose low-order 6 bits with the current value ofm_Hashto give the newm_Hash.You know that rotating and exclusive-oring are common operations in calculating a hash.
EDIT: @schnaader pointed out the bug in the original code: that code forgot to do the other leg of the rotate: shifting the low-order 26 bits left by 6. To fix that, the code should read something like:
As to your
HasHash( )function: you should know that sayingreturn (m_Hash & val) == 0;will return TRUE under many conditions, including some you might not want. For example, the function will return TRUE if
m_Hash == 0xC0andval == 0x03.