1

I've a list of arbitrary strings. I would like to convert these to a hexadecimal color code.

The code should not be random, as it is essential that the method must return the same color code each time I convert the same string.

SOLUTION:

public string GetColorCode(string value)
{
    var i = value.GetHashCode() & 0x00FFFFFF;
    return i.ToString("X6");
}
2
  • 1
    Am confused...you want to convert or map? Commented Nov 13, 2012 at 11:57
  • The solution should really be added as your own answer to the question, shouldn't it? I realize this would take the points from the answerer, but it would offer better content for later visitors (like me) and better follows the SO format. Commented Nov 19, 2014 at 20:09

1 Answer 1

3

You can use GetHashCode() as a starting point. Since GetHasCode() returns a full integer and you usually need just 3 bytes to define a color in RGB, you have to skip the noin significant part by doing either:

var color = str.GetHashCode() & 0x00FFFFFF;

or

 var color = str.GetHashCode()>>8;

this guarantee having same string, same color.

Sign up to request clarification or add additional context in comments.

3 Comments

How can I convert this color integer into a hexadecimal color code? I've tried color.ToString("X"), but this does not always return a hexadecimal code with 6 digits.
ToString("X6") will add leading zeroes if necessary, if that's your problem.
@DennisMadsen I corrected the answer with >>8, the ToString("X6") as suggested by Rawlign is the way to go after my suggestion.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.