我有以下对string
进行哈希处理的函数:
public static uint hashString(string myString)
{
uint hash = 0;
foreach (char c in myString)
{
hash *= 0x1F;
hash += c;
}
return hash;
}
因此,如果我想对
hello
进行哈希处理,它将产生99162322
。是否可以编写一个接受
number
并吐出string
的反向函数(假设string
结果未知)? 最佳答案
由于您不使用加密哈希,因此您的实现很容易反转(即返回一些具有给定哈希值的string
)
码:
public static uint hashString(string myString) {
//DONE: validate public methods' parameters
if (null == myString)
return 0;
uint hash = 0;
//DONE: hash function must never throw exceptions
unchecked {
foreach (char c in myString) {
hash *= 0x1F;
hash += c;
}
}
return hash;
}
private static string HashReverse(uint value) {
StringBuilder sb = new StringBuilder();
for (; value > 0; value /= 31)
sb.Append((char)(value % 31));
return string.Concat(sb.ToString().Reverse());
}
演示:(给定一个
hash
我们产生一个string
并从中计算出hash
进行检查)uint[] tests = new uint[] {
99162322,
123,
456
};
// Since the string can contain control characters, let's provide its Dump
string Dump(string value) => string.Join(" ", value.Select(c =>((int) c).ToString("x4")));
string report = string.Join(Environment.NewLine, tests
.Select(test => new {
test,
reversed = HashReverse(test)
})
.Select(item => $"{item.test,9} :: {Dump(item.reversed),-30} :: {hashString(item.reversed),9}"));
Console.WriteLine(report);
结果:
99162322 :: 0003 000e 000b 0012 0012 0012 :: 99162322
123 :: 0003 001e :: 123
456 :: 000e 0016 :: 456
请注意,许多
string
产生相同的哈希值(例如"hello"
和我的"\u0003\u000e\u000b\u0012\u0012\u0012"
)