Luka Lovre
Luka Lovre

Reputation: 13

How to convert random text into an integer

I have different rectangle objects that each have an unique ID generated via a Guid.

Example ID: "fdd4551f-0087-48ee-b764-3713b5107ac9"

I want to convert that string into an integer from 0 to 256 so I can assign a random color to each object depending on their IDs.

Example of expected results:

For

"fdd4551f-0087-48ee-b764-3713b5107ac9" = 186

"48d32306-2861-4e78-b57e-9a02ce92f8ed"  = 35 

I don't really care what the numbers are except that I always get the same result with the same random string.

Upvotes: 0

Views: 335

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 416131

Given the relatively loose requirements, this can be a one-liner:

static int GetNumberForString(string guid, int limit)
{
    return Math.Abs(guid.GetHashCode()) % limit;
}

Upvotes: 3

Related Questions