title: Hash and modulo strings to have equivalent results between C# and Python
body: <p>I have need to group strings into ten different groups in a deterministic fashion, with some level of uniformity.  The strings are identifiers that come from different sources, all with different (basically unknown) formats.</p>
  
  <p>To accomplish this I decided to hash the strings and mod by 10.  However I am going to be doing this in two different locations and I need their results to be consistent, one is a C# app and the other is a python one.</p>
  
  <p>To ensure consistent hashing I have decided to go with MD5 (reasonably fast and consistent).  Python already has this in the <a href="https://docs.python.org/2/library/md5.html" rel="nofollow noreferrer">hashlib</a> library and C# has one as in <a href="https://msdn.microsoft.com/en-us/library/system.security.cryptography.md5%28v=vs.110%29.aspx" rel="nofollow noreferrer">Cryptography</a></p>
  
  <p>However I need to int and modulo these numbers with consistency.  In python this is easy</p>
  
  <pre><code>md5 = hashlib.md5()
  md5.update(my_string)
  int(md5.hexdigest(), 16) % 10
  </code></pre>
  
  <p>But I can't just do this in C# as I only have 64 bit integers.  So my thought is to just grab the last 16 characters from the hex.  In python</p>
  
  <pre><code>int(md5.hexdigest()[-16:]) % 10
  </code></pre>
  
  <p>Then in C#</p>
  
  <pre><code>// hashString filled via MD5 code in the C# link above
  string subHash = hashString.Substring(hashString.Length - 16);
  Convert.ToUInt64(subHash, 16) % 10;
  </code></pre>
  
  <p>Now my questions are these.  Are these two methods guaranteed to be equivalent?  Is MD5 a good choice here?  It's certainly consistent but if there is something faster that would be ideal.  Is grabbing the last 16 characters the best way to prevent overflow?</p>