2013-05-14 45 views
-1

我有字母数字字符串值。我需要用一个整数值来表示每个字符串。将字符串转换为特定范围之间的整数

生成的整数必须在30到150之间。
多个字符串可以具有相同的整数值。
特定的字符串必须在每次运行时给出相同的整数值。
加密不重要,字符串值不重要。
更快的计算是首选。
所有整数都没有相同的值。我试过intval(),但它给了我零。然后我尝试了md5sha1,这给了我很长的字符串。我试过base_convert,但无法做到。

+3

你能你的代码添加到这个问题,好吗? – andrewsi

+3

这就是所谓的“哈希”,谷歌它。 – Barmar

+6

你说你的问题的方式,代表每个字符串的数量为42会符合你的规格。 – collapsar

回答

2

这将需要一个哈希函数。你的范围是150-30=120所以你需要模120(% 120)的结果,并添加30

在PHP中最标准的散列函数(MD5,SHA)是出于安全目的,并返回一个字符串,这些都不是非常有用的。在这种情况下,您可以使用循环冗余校验:http://php.net/crc32。这不是一个哈希(值不均匀分布),但可能足够接近您的目的。

$stringhash = crc32($string) % 120 + 30; 

如果您需要更均匀的分布,您还可以使用简单的标准散列,例如, MD5,但这是慢的。

// Take the first 8 alphanumeric digits of the hash (= 32 bits) because we want to keep an int and not convert it to a floating point 
$stringhash = intval(substr(md5($string), 0, 8), 16) % 120 + 30; 
+0

谢谢,这很酷。 – trante

0

通过使用@帝特的回答我完成我的功能是这样的:

public function convertStringToInteger($string, $min, $max, $dateDepended=FALSE) { 
    $interval = $max-$min; 
    if ($dateDepended) { 
     $addMore=strtotime("today"); 
    } else { 
     $addMore=0; 
    } 
    return ((crc32($string)+$addMore) % $interval) + $min; 
} 

convertStringToInteger("myword",30,150,TRUE);