将字符串哈希为 0-19 之间的整数
我想知道如何将字符串值(例如:“myObjectName”)哈希为 0-19 之间的 int 值 我保证不超过 20 个唯一字符串值。
谢谢
I was wondering how I would hash a string value (ex: "myObjectName") to int values between 0-19
I'm guaranteed to have no more than 20 unique string values.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
进行 md5 求和,转换为数字并模 20。例如,在 PHP 中:
hexdec(substr(md5("hello"), 1, 8)) % 20
需要 substr() 以便数字可以转换为整数。
Do md5 sum, convert to number and do modulo 20. E.g. in PHP:
hexdec(substr(md5("hello"), 1, 8)) % 20
The substr() is needed so that the number can be converted to integer.
您可以使用您喜欢的任何类型的散列,但在这种情况下,您可以将字符的 ASCII 值(或 unicode 代码点,如果您愿意)相加,并对结果应用模 20。它会给你一个从 0 到 19 的数字。
但这并不能保证产生一个唯一标识你的 20 个字符串的数字。没有任何哈希算法可以保证对 20 个随机字符串的集合进行哈希处理会为每个字符串生成唯一的代码。
You could use any sort of hashing you like, but in this case, you could do with adding up the ASCII values (or unicode code point, if you like) of the characters, and apply modulo 20 to the result. It will give you a number from 0 to 19.
But this is nog guaranteed to result in a number that uniquely identifies your 20 strings. No hashing algorithm will guarantee that hashing a collection of 20 random strings will result in a unique code for each string..
按照建议添加我的评论作为答案:
我建议散列不是您应该在此处遵循的确切路径。
一种方法是使用字典(如 Python 中的内置数据结构),该字典具有字符串的键值对和 1-20(或 0 - 19)之间的数字。
当您阅读或查看每个字符串时,您可以检查字典条目是否存在,如果存在,则执行需要执行的操作,如果不存在,则使用下一个可用数字(通过查看字典中现有条目的数量生成)创建一个新的字典条目。
Adding my comment as an answer as suggested:
I would suggest that hashing isn't the exact path you should follow here.
One method would be using a dictionary (like the built in data structure in Python) that has a key-value pair of your string and a number from 1-20 (or 0 - 19)
As you read or see each string, you could check to see if a dictionary entry exists, if so, do whatever needs to be done, if not, create a new dictionary entry with the next available number (generated by looking at the number of existing entries in the dictionary).