反向字符串哈希函数

问题描述 投票:3回答:2

我具有以下功能,[[哈希 a string

public static uint hashString(string myString) { uint hash = 0; foreach (char c in myString) { hash *= 0x1F; hash += c; } return hash; }
因此,如果我想对hello进行散列,它将产生99162322

是否可以编写一个

reverse函数,该函数接受number并吐出string(假设string 结果

未知)]
c# hash reverse
2个回答
3
投票
reverse(即,返回具有给定哈希值的[[some 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()); }

Demo:

(给定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产生same哈希值(例如"hello"和我的"\u0003\u000e\u000b\u0012\u0012\u0012"

1
投票
© www.soinside.com 2019 - 2024. All rights reserved.