将字符串编码为整数 .NET

发布于 2024-09-05 06:16:08 字数 220 浏览 4 评论 0原文

我有一个字符串,我想将其唯一地表示为整数。

例如: A3FJEI = 34950140

我将如何编写 EncodeAsInteger(string) 方法。我知道字符串中的字符数量会使整数大大增加,迫使该值变成long,而不是int。

由于我需要该值是整数,因此我不需要数字表示对于字符串来说是完全唯一的。

也许我可以遍历字符串的所有字符并对字符的数字键码求和。

I have a string that I would like represented uniquely as an integer.

For example: A3FJEI = 34950140

How would I go about writing a EncodeAsInteger(string) method. I understand that the amount of characters in the string will make the integer increase greatly, forcing the value to become a long, not an int.

Since I need the value to be an integer, I don't need the numerical representation to be entirely unique to the string.

Maybe I can foreach through all the characters of the string and sum the numerical keycode of the character.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

摇划花蜜的午后 2024-09-12 06:16:08

如果这些是您的要求:

  1. 某种字符串→整数映射。
  2. 整数不必是唯一的。

那么你很幸运,因为这正是 GetHashCode() 方法可以! MSDN 页面提供了一些示例哈希代码。请注意,这些是完全任意的,并且可能在 CLR 的未来版本中更改。

“”的哈希码是:0x00001505, 5381
“a”的哈希码是:0x0002B5C4, 177604
“ab”的哈希码是:0x00596E26, 5860902
“abc”的哈希码是:0x0B873285, 193409669
“abd”的哈希码是:0x0B873282, 193409666
“abe”的哈希码是:0x0B873283, 193409667
“abcdef”的哈希码是:0x4DDB4BE2, 1306217442
“abcdeg”的哈希码是:0x4DDB4BE3, 1306217443
“abcdeh”的哈希码是:0x4DDB4BEC,1306217452
“abcdei”的哈希码是:0x4DDB4BED,1306217453
“Abcdeg”的哈希码是:0x941C4FC3,-1810083901
“Abcdeh”的哈希码是:0x941C4FCC,-1810083892
“Abcdei”的哈希码是:0x941C4FCD,-1810083891

If these are your requirements:

  1. Some sort of string → integer mapping.
  2. Integers don't have to be unique.

Then you're in luck, because this is exactly what the GetHashCode() method does! The MSDN page gives some sample hash codes. Note that these are completely arbitrary and can change in future versions of the CLR.

The hash code for "" is: 0x00001505, 5381
The hash code for "a" is: 0x0002B5C4, 177604
The hash code for "ab" is: 0x00596E26, 5860902
The hash code for "abc" is: 0x0B873285, 193409669
The hash code for "abd" is: 0x0B873282, 193409666
The hash code for "abe" is: 0x0B873283, 193409667
The hash code for "abcdef" is: 0x4DDB4BE2, 1306217442
The hash code for "abcdeg" is: 0x4DDB4BE3, 1306217443
The hash code for "abcdeh" is: 0x4DDB4BEC, 1306217452
The hash code for "abcdei" is: 0x4DDB4BED, 1306217453
The hash code for "Abcdeg" is: 0x941C4FC3, -1810083901
The hash code for "Abcdeh" is: 0x941C4FCC, -1810083892
The hash code for "Abcdei" is: 0x941C4FCD, -1810083891

南渊 2024-09-12 06:16:08
    protected int EncodeStringAsInt(string value)
    {
        return value.ToCharArray().Sum(c => Convert.ToInt32(c));
    }
    protected int EncodeStringAsInt(string value)
    {
        return value.ToCharArray().Sum(c => Convert.ToInt32(c));
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文