DaRoGa DaRoGa - 1 year ago 78
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


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 Source

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
      .Select(item => item.ToString("X2")));


 String result = md5_hash3(r.Employee.Name); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download