This one works. For 32-bit (PHP_INT_SIZE == 4) and 64-bit integers (PHP_INT_SIZE == 8):
function string2color($str) {
$hash = 0;
for ($i = 0; $i < strlen($str); $i++) {
$encdoe_str = charCodeAt($str,$i);
$hash = $encdoe_str+(_32bitleftshift($hash, 5) - $hash);
}
$colour = '#';
for ($i = 0; $i < 3; $i++) {
$value = _32bitrightshift($hash, ($i * 8)) & 0xFF;
$hex = '00' . base_convert($value, 10, 16);
$colour .= substr($hex, -2);
}
return $colour;
}
function charCodeAt($str, $index){
$char = mb_substr($str, $index, 1, 'UTF-8');
if (mb_check_encoding($char, 'UTF-8'))
{
$ret = mb_convert_encoding($char, 'UTF-32BE', 'UTF-8');
return hexdec(bin2hex($ret));
} else {
return null;
}
}
function _32bitleftshift($number, $steps)
{
$result = 0;
if (strlen(decbin($number)) + $steps <= 31) {
$result = $number << $steps;
} else {
$binary = decbin($number).str_repeat("0", $steps);
$binary = substr($binary, strlen($binary) - 32);
if ($binary{0} == "1") {
$binary = substr($binary, strlen($binary) - 31);
$binary_1s_complement = "";
for ($i = 0; $i <= 30; $i++) {
$binary_1s_complement .= ($binary{$i} == "0"? "1" : "0");
}
$binary_2s_complement = decbin(bindec($binary_1s_complement) + 1);
$result = -1 * bindec($binary_2s_complement);
} else {
$result = bindec($binary);
}
}
return $result;
}
function _32bitrightshift($x, $c) {
$x = intval ($x);
$nmaxBits = PHP_INT_SIZE * 8;
$c %= $nmaxBits;
if ($c)
return $x >> $c & ~ (-1 << $nmaxBits - $c);
else
return $x;
}
echo string2color('b11b92c6-cdb8-488b-925c-0a0651b1b5b3');
source
share