Compute Hex Color Code for an Arbitrary String

Compute hex color code for an arbitrary string

If you don't really care about the "meaning" of the color you can just split up the bits of the int (remove the first for just RGB instead of ARGB)

String [] programs = {"XYZ", "TEST1", "TEST2", "TEST3", "SDFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"};

for(int i = 0; i < programs.length; i++) {
System.out.println( programs[i] + " -- " + intToARGB(programs[i].hashCode()));
}
....
public static String intToARGB(int i){
return Integer.toHexString(((i>>24)&0xFF))+
Integer.toHexString(((i>>16)&0xFF))+
Integer.toHexString(((i>>8)&0xFF))+
Integer.toHexString((i&0xFF));
}

Compute hex color code for an arbitrary string in Objective c ios 7

There are probably many ways. Here's one:

NSString *someString = ... // some string to "convert" to a color
NSInteger hash = someString.hash;
int red = (hash >> 16) & 0xFF;
int green = (hash >> 8) & 0xFF;
int blue = hash & 0xFF;
UIColor *someColor = [UIColor colorWithRed:red / 255.0 green:green / 255.0 blue:blue / 255.0 alpha:1.0];

The same string will always give the same color. Different strings will generally give different colors but it is possible that two different strings could give the same color.

Create a hexadecimal colour based on a string with JavaScript

Just porting over the Java from Compute hex color code for an arbitrary string to Javascript:

function hashCode(str) { // java String#hashCode
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
return hash;
}

function intToRGB(i){
var c = (i & 0x00FFFFFF)
.toString(16)
.toUpperCase();

return "00000".substring(0, 6 - c.length) + c;
}

To convert you would do:

intToRGB(hashCode(your_string))

How to convert arbitrary string to hexadecimal color code

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.

How to create standalone type for a HEX color string?

You probably already tried to do it the naive way, where you make a union of all the possibilites, and it does actually work for a three-digit hex color, but not for a longer one (see code below). I suspect, to answer your question directly, that it's impossible to make a 'standalone' type that works for all six-digit hex colors, because this would have to be a union of millions of elements.

type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'a' | 'b' | 'c' | 'd' | 'e'| 'f' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F';
type ShortColor = `#${Digit}${Digit}${Digit}`;
type LongColor = `#${Digit}${Digit}${Digit}${Digit}${Digit}${Digit}`; // Error
type Color = ShortColor | LongColor;

const someColor: ShortColor = '#fc2';
const badColor: ShortColor = '#cg2'; // Error

That said, I think your solution is a fine one itself. I did notice your code doesn't work on newer versions of TypeScript, so I made a slight modification to it so that it does work with the latest version, 4.4.0-beta. The code is a bit simpler and avoids generating too large of a union by doing the conditional check in two steps:

type HexDigit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'a' | 'b' | 'c' | 'd' | 'e'| 'f' | 'A' | 'B' | 'C' | 'D' | 'E'| 'F';
type HexColor<T extends string> =
T extends `#${HexDigit}${HexDigit}${HexDigit}${infer Rest1}`
? (Rest1 extends ``
? T // three-digit hex color
: (
Rest1 extends `${HexDigit}${HexDigit}${HexDigit}`
? T // six-digit hex color
: never
)
)
: never;

function hex<T extends string>(s: HexColor<T>): T {
return s;
}

// All valid
hex('#ffffff');
hex('#fff');
hex('#000');
hex('#123456');
hex('#abcdef');
hex('#012def');
hex('#ABCDEF');

Finally, I might suggest that you use type brands to create a type which signifies that a string is a valid hex color, and only use your hex function to create strings of that type? In the example below, you could simply use Color throughout your codebase and only need to rely on the hex helper function when specifically making a Color from a string literal for the first time. I don't know if this'll meet your exact ideal usecase, because you do still need to use your hex helper wherever a literal is declared, but it gets you pretty close:

type Color = string & { __type: "HexColor" };
function hex<T extends string>(s: HexColor<T>): Color {
return s;
}

const color: Color = hex('#aaa');
const theme: Record<string, Color> = {
backgroundColor: hex('#ff0000'),
color: hex('#0f0'),
};

generate a unique hex color from string

You could use an object's hash value to generate a color.

Here's a quick & dirty solution that produces RGBA values.

using System.Linq;

namespace System {
static class StringExtensions {
public static string ToHexColor(this string text) {
if (text == null) text = string.Empty;

int hash = text.GetHashCode();

return $"#{hash:X8}";
}
}
}

You can use it with

string colorString = "My random string".ToHexColor();

How to identify a given string is hex color format

Note: This is strictly for validation, i.e. accepting a valid hex color. For actual parsing you won't get the individual parts out of this.

^#(?:[0-9a-fA-F]{3}){1,2}$

For ARGB:

^#(?:[0-9a-fA-F]{3,4}){1,2}$

Dissection:

^              anchor for start of string
# the literal #
( start of group
?: indicate a non-capturing group that doesn't generate backreferences
[0-9a-fA-F] hexadecimal digit
{3} three times
) end of group
{1,2} repeat either once or twice
$ anchor for end of string

This will match an arbitrary hexadecimal color value that can be used in CSS, such as #91bf4a or #f13.

Converting a random string into a hex colour

var color_codes = {};
function stringToColorCode(str) {
return (str in color_codes) ? color_codes[str] : (color_codes[str] = '#'+ ('000000' + (Math.random()*0xFFFFFF<<0).toString(16)).slice(-6));
}

How do I create a random hex string that represents a color?

Easiest way is to use String.Format and use the hexadecimal format for the argument.

var random = new Random();
var color = String.Format("#{0:X6}", random.Next(0x1000000)); // = "#A197B9"


Related Topics



Leave a reply



Submit