Android / Java: convert any string to color (hexadecimal)

Is there a way to generate color from any String in Java / Android, such as the Encrypt / Hash function?

Example: The string "Home" generates a color of the type "# FF1234".
The string "Sky" generates a color such as "# 00CC33", ...

No randomization. Thus, the system will always calculate the same colors for these lines

thank

EDIT: Lines freely defined by user

+5
source share
5 answers

the String.hashCode()will return an int value, so it's just a matter of turning this into a hex value.

String s = "Home";
String color = String.format("#%X", s.hashCode());
+8
source

Try to see how to create a message digest of your string.

http://www.mkyong.com/java/java-sha-hashing-example/

, , , . , , .

+3

:

String opacity = "#99"; //opacity between 00-ff
String hexColor = String.format(
        opacity + "%06X", (0xFFFFFF & anyString.hashCode()));

android :
https://gist.github.com/odedhb/79d9ea471c10c040245e

+3

, .

, , . .

Ascii , , . , , . IE. FFFFFF , .

//pseudocode
counter = 0;
foreach(char in string){
    counter+=(int)char;

}
counter = convertToHex(counter)%0xffffff;
string x = "#"+counter.toString();

,

string x = "#"+hexVal.toString();

, .

+1

You can try something like:

String s = "Home";
byte[] b = s.getBytes("US-ASCII");
StringBuffer hexString = new StringBuffer();
for (int i=0;i<b.length;i++) {
    hexString.append(Integer.toHexString(0xFF & b[i]));
    }
String finalHex = "#" + hexString.substring(0,6);
System.out.println(finalHex);

Generates a hex code: #486f6d

In the same way, create hex for all Stringyou want and add them to HashMapas a key-value pair.

0
source

All Articles