[英]Generate A Short Integer From A Unique String Without .GetHashCode()
I'd like to generate a short integer when given a unique string.当给定唯一字符串时,我想生成一个短整数。 Note the string will never be more than 3 characters long, only alpha characters, can be either upper or lower case.
请注意,字符串的长度永远不会超过 3 个字符,只有字母字符,可以是大写或小写。 For instance,
AB
should not return the same value as BA
.例如,
AB
不应返回与BA
相同的值。 I tried something like the following (below), only to run into BA
being equal to AK
:我尝试了类似以下(如下)的方法,只是遇到
BA
等于AK
:
public static class StringExtensions
{
public static int StringToASCIIValue(this string str)
{
if (string.IsNullOrWhiteSpace(str))
throw new ArgumentException("string must not be null or whitespace");
int result = 0;
foreach (char singleChar in str)
{
result = 10 * result + singleChar - '0';
}
return result;
}
}
Here is a simple way to accomplish this.这是实现此目的的简单方法。 No two results will be the same.
没有两个结果是相同的。 We take the string, then for each character in it we append the ascii value to a string builder.
我们获取字符串,然后对于其中的每个字符,我们将 ascii 值附加到字符串构建器。 When we are done we can output a unique integer for that character combination.
完成后,我们可以为该字符组合输出一个唯一的整数。
string first = "AB";
StringBuilder stringBuilder = new StringBuilder();
foreach(char c in first)
{
stringBuilder.Append((int)c);
}
Console.WriteLine(stringBuilder.ToString());
Output输出
6566
If you're really sure you're not ever looking at more than 3 alphabetic ( AZ
or az
) characters, you should be able to just get the ASCII
encoded bytes and convert them directly to an int
.如果您真的确定您不会看到超过 3 个字母(
AZ
或az
)字符,您应该能够获取ASCII
编码的字节并将它们直接转换为int
。
public static class StringExtensions
{
public static int ToInt32(this string str)
{
// Checks for null omitted.
var ascii = System.Text.Encoding.ASCII.GetBytes(str);
int result = 0;
for (int i = 0; i < ascii.Length; i++)
{
result = result | (ascii[i] << (i * 8));
}
return result;
}
}
If it matters, you can then take that int
back to the string
that generated it.如果重要,您可以将该
int
带回生成它的string
。
public static class StringExtensions
{
public static string AsciiIntBackToString(this int value)
{
var bytes = BitConverter
.GetBytes(value)
.Where(b => b > 0)
.ToArray();
return System.Text.Encoding.ASCII.GetString(bytes);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.