将字符串(单词)转换为long

时间:2018-12-19 06:36:57

标签: c# .net string casting type-conversion

我想从“ Testcase1”,“ Testcase2”等字符串创建唯一的ID。因此,我想将字符串分别转换为整数,很长。

我已经尝试过了,但是我认为数字/ ID既不是唯一的,也不是正确的。我想将整个单词转换成数字。

long numberId = 0;
foreach (var character in testString.ToCharArray())
{
    numberId +=  Convert.ToInt16(character);
}

5 个答案:

答案 0 :(得分:0)

怎么样?

var sha = System.Security.Cryptography.SHA512.Create();
var inputBytes = System.Text.Encoding.ASCII.GetBytes("Test case");
var hash = sha.ComputeHash(inputBytes);
var result = BitConverter.ToInt64(hash);

答案 1 :(得分:0)

我没有证据,但是我认为以下方法会产生独特的价值。

public static void Main()
{
    long numberId = 0;
    var testString = "Testcase3";
    long multiplier = (long)Math.Pow(10,testString.Length);
    foreach (var character in testString.ToCharArray())
    {
        numberId +=  Convert.ToInt16(character)*multiplier;
        multiplier /=10;
    }
    Console.WriteLine(numberId);
}

答案 2 :(得分:0)

不确定这是否是您想要的:

x = 0
filename = 'product{}.csv'.format(x)

输出:

Testcase1 => 1880

Testcase2 => 1788

答案 3 :(得分:0)

如果它需要唯一,那么long将不起作用,因为字符串的数量超出了long的大小。如果您真的需要一个唯一的数字,则可以使用System.Numerics.BigInteger的构造函数,该构造函数采用字节数组,例如

var id = new BigInteger(Encoding.Unicode.GetBytes("string goes here"));

根据您的操作,这可能有用也可能没有用。

答案 4 :(得分:0)

如何使用基于测试字符串的字节数组总和实现此实现:

    long uniqueId = "Testcase1".SelectMany(BitConverter.GetBytes).ToArray().Sum(c=> c);
    long uniqueId2 = "Testcase2".SelectMany(BitConverter.GetBytes).ToArray().Sum(c => c);

Testcase1-> 877

Testcase2-> 878