Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a random string into a hex colour

Tags:

javascript

I have a table of action logs in my application. I want to assign rows a random colour based on the sessionID of that entry to help see patterns/grouped actions.

I have this so far:

console.log(stringToColorCode('mj3bPTCbIAVoNr93me1I'));

function stringToColorCode(str) {
    return '#'+ ('000000' + (Math.random()*0xFFFFFF<<0).toString(16)).slice(-6);
}

However I need to replace Math.random() with my string-integer, are there any techniques for converting a string to a random number that remains consistent with the random string?

like image 958
Titan Avatar asked Jul 24 '13 22:07

Titan


People also ask

Can we convert string to hex?

Get the desired String. Create an empty StringBuffer object. Convert it into a character array using the toCharArray() method of the String class.

How do I generate a random hex color in C#?

Try reusing the Random objects throughout the loop. Or var color = $"#{random. Next(0x1000000):X6}"; with string interpolation in C# 6.


1 Answers

As requested, posting this as an awswer

var stringHexNumber = (                       // 1
    parseInt(                                 // 2
        parseInt('mj3bPTCbIAVoNr93me1I', 36)  // 3
            .toExponential()                  // 4
            .slice(2,-5)                      // 5
    , 10) & 0xFFFFFF                          // 6
).toString(16).toUpperCase(); // "32EF01"     // 7

So, what's going on?

  1. Things start on line 3 where 'mj3bPTCbIAVoNr93me1I' gets converted to an Integer, say x, by interpreting it as a base-36 number.
  2. Next, x is put into it's exponential form as a String on line 4. This is because with that many characters, x can be huge, this example is around 8e30, so convert it to a form that will be pretty standard.
  3. After this, line 5 trims off the beginning and end so you'll be left with just digits, e.g. '8.123e+30'.slice(2, -5) becomes '12'.
  4. Now we go back to line 2, where this gets converted back into an Integer again, this time in base 10.
  5. Then, line 6 truncates this number down to the range 0..16777215 (=== 0xFFFFFF) using a fast bitwise AND. This will also convert NaN to 0.
  6. Finally, line 7 converts this back into the upper case hex format we are used to seeing colours in, by writing the number in base 16 and changing the case.

If you want to use this, you may also want to ensure that the final number is 6 digits and stick a # on the front, which can be done via

'#' + ('000000' + stringHexNumber).slice(-6); // "#32EF01"
like image 158
Paul S. Avatar answered Oct 10 '22 11:10

Paul S.