Storing Hash Codes

  • Thread starter Thread starter Brian
  • Start date Start date
B

Brian

I know this is the wrong way to do it, but maybe someone can tell me the
right way to do it...

I have two different databases that I need to synchronize. The database
doesn't have keys exactly, but it does provide a rowid function.

So, I am storing a dictionary of <string, long>, string being the rowid
and long being a sum of the hash code for each column in the row.

With this dictionary, it is very easy to determine if a row is new, has
changed, or is already in sync with the target system:

* If I have a rowid that doesn't exist in the dictionary, then I know
it is a new row and I can call my insert code.

* If I have a rowid that exists in the dictionary, and the sum of hash
codes is the same as in my dictionary, then I know that the row has not
changed and there is no action to take.

* If I have a rowid that exists in the dictionary, and the sum of hash
codes is not the same as my dictionary, then I know the row of has
changed, and I need to call my update code.

-----

So, my question is, with this situation, how can I get the same results,
but not store GetHashCode(). I need some kind of "stable" hash
calculation. And it needs to take all kinds of objects; string, int,
decimal, double, etc.

I started to think I could just use a hash code on string and call
ToString() on each column, but this looks just as dangerous as trusting
GetHashCode() not to change.


Thanks for any tips...
Brian
 
So, my question is, with this situation, how can I get the same results,
but not store GetHashCode(). I need some kind of "stable" hash
calculation. And it needs to take all kinds of objects; string, int,
decimal, double, etc.

Use an MD5 hash (or something similar). You'll need to convert each
type into a stable binary representation, but then you can add each
field to the hash as you go.
 
And to add to my own reply, here's a sample from an application I wrote a few
years ago:

public static byte[] HashBytes512(string pw, bool UE)
{
byte[] pwBytes;
if (UE)
{
pwBytes = Encoding.Unicode.GetBytes(pw);
}
else
{
pwBytes = Encoding.ASCII.GetBytes(pw);
}
SHA512Managed sha = new SHA512Managed();
byte[] hashBytes = sha.ComputeHash(pwBytes);
return hashBytes;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top