2012-03-20 64 views
1

我试图将网址映射到范围[0,50]中用于移植的数字,它应该在范围内均匀分布,这样就不会损坏端口。将网址映射到随机端口范围

下面是我的代码,但我可以找出为什么模数不适合我。

$fetch_url = "http://74.125.224.72/profile/user"; 
    $hash = sha1($fetch_url); 
    $hasher = substr($hash,1,50); 
    $port_index = hexdec($hasher)%50; 
    $port = 8700 + $port_index; 

似乎一切工作到$ port_index返回0.请记住,“用户”是每次都不同的实际用户名。

的最终目标是下面写:

http://74.125.224.72/profile/j - port = 8701 
    http://74.125.224.72/profile/m - port = 8702 
    http://74.125.224.72/profile/p - port = 8703 

而且应该是每次这种方式在用户登录并点击他们的个人资料。

任何想法?

感谢 -J

回答

1

我相信这个问题是一个SHA1哈希的hexdec转换是如此巨大,PHP还挺停止处理它作为一个数字。你应该修剪散列和十六进制的最后几个字符。看起来你可能一直在用你的substr,但是sha1是40个字符,你做了50个substr。那50是一个错误吗?

正因为如此,hexdec返回类似于'5.4627305075531E + 46'的东西,它不会正确地穿过模量。试试:

$fetch_url = "http://74.125.224.72/profile/user"; 
$hash = sha1($fetch_url); 
$hasher = substr($hash,-5); // get last 5 
$port_index = hexdec($hasher)%50; 
$port = 8700 + $port_index; 
+0

这样做。谢谢kingcoyote。 – JMP 2012-03-21 00:12:40