DaRoGa DaRoGa - 3 months ago 13
C# Question

C# - Create a hash of a string to an integer between a particular range

I am trying to implement a form of random colour generator.

What i am planning on doing, is to create a hash of a string (Employee's name) to generate a hexadecimal value (#0 to #FFFFFF), therefore causing that employee to always correspond to the same colour.

Does anybody have an approach to do this that may work?

Thanks in Advance

EDIT

MD5 hasher = MD5.Create();
var hashed = hasher.ComputeHash(Encoding.UTF8.GetBytes(r.Employee.Name));
var intColor = BitConverter.ToInt32(hashed, 0);
color = intColor.ToString("X");


This is what i have so far, however there seems to be an issue with it somewhere as it displays the standard blue colour for everything

Answer

Since #0 to #FFFFFF range is 3 bytes, we can compute the hash as usual and then take, say, first 3 bytes:

public static String md5_hash3(String value) {
  using (var hash = MD5.Create()) {
    return String.Concat(hash
      .ComputeHash(Encoding.UTF8.GetBytes(value))
      .Take(3)
      .Select(item => item.ToString("X2")));
  }
}

...

 String result = md5_hash3(r.Employee.Name);