将 md5(或者可能是另一种散列方法?)转换为整数的算法,可以设置可能的结果整数范围(例如:1-10000)?
该主题几乎描述了我们想要完成的任务。
a) 从可能的整数范围开始,例如 1 到 10000。
b) 获取任何 md5 哈希值,通过此算法运行它。
c) 弹出的结果将是 1 到 10000 之间的整数。
我们也愿意使用另一种哈希方法。
理想情况下,流程应该是这样的:
string -> md5(string) -> algo(md5(string),range) -> resulting integer within range
这样的事情可能吗?
最后注意:范围总是从 1 开始。
如果您有答案,请随意发布一般想法,或者如果您愿意,php 片段也可以:)
谢谢!
the topic pretty much describes what we would like to accomplish.
a) start with a possible range of integers, for example, 1 to 10000.
b) take any md5 hash, run it thru this algo.
c) result that pops out will be an integer between 1 to 10000.
we are open to using another hashing method too.
the flow would ideally look like this:
string -> md5(string) -> algo(md5(string),range) -> resulting integer within range
is something like this possible?
final note: the range will always start with 1.
if you have an answer, feel free to post just the general idea, or if you so desire, php snippet works too :)
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于 MD5(和 SHA-1 等)将为您提供 128 位数据(在 PHP 中,您将以十六进制字符串表示法获得它,因此您需要首先将其转换为整数)。该数字模 10000 将为您提供整数。
但请注意,许多不同的哈希值将转换为相同的整数;这对于任何类型的整数范围转换都是不可避免的,因为
取模
运算本质上映射了一组更大的数字(在本例中为 128 位,即来自0 到 340,282,366,920,938,463,463,374,607,431,768,211,456)到较小的一组数字(少于 17 位,数字从 1 到 100,000)。Since MD5 (and SHA-1, etc.) will give you 128 bits of data (in PHP, you'll get it in hexadecimal string notation, so you need to convert it to an integer first). That number modulo 10000 will give you your integer.
Note however that many different hashes will convert to the same integer; this is unavoidable with any sort of conversion to your integer range, as the
modulo
operation essentially maps a larger set of numbers (in this case, 128 bits, that is numbers from 0 to 340,282,366,920,938,463,463,374,607,431,768,211,456) to a smaller set of numbers (less than 17 bits, numbers from 1 to 100,000).由于我们想要的范围始终从 1 开始,因此以下代码效果很好。所有功劳都归功于 Piskvor,因为他提供了如何进行此操作的基本想法。
下面的代码可以完成我们想要的事情。如果这可以(不是代码,仅供参考,但如果这个想法)有任何改进,请插话。运行下面的代码将产生 6305 / 10000 个唯一结果。在我们的例子中这已经足够好了。
享受!
since the range that we want will always start at 1, the following works great. all credit goes to Piskvor, as he was the one who provided the basic idea of how to go at this.
the code below seams to accomplish what we want. please chime in if this can be (not the code, its just for reference, but if the idea) improved at all. running the code below will result in 6305 / 10000 unique results. that in our case is good enough.
enjoy!