Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Convert.ToInt32出现问题,获取错误索引和长度时必须引用字符串中的某个位置_C#_Linq_Checksum_Crc - Fatal编程技术网

C# Convert.ToInt32出现问题,获取错误索引和长度时必须引用字符串中的某个位置

C# Convert.ToInt32出现问题,获取错误索引和长度时必须引用字符串中的某个位置,c#,linq,checksum,crc,C#,Linq,Checksum,Crc,我们需要从字符串中获取crc代码。 例如:字符串为(ff03c1),crc代码为(3d) 在字符串少于186个字符之前,以下代码将正常工作。 示例字符串: 20000F38080000D1080020110800190D0000000000000000000000000000000020000F38080000D1080020110800190D000000000000000000000000000000020000F38080000D1080020110800190D0000000000000

我们需要从字符串中获取crc代码。 例如:字符串为(ff03c1),crc代码为(3d)

在字符串少于186个字符之前,以下代码将正常工作。 示例字符串:

20000F38080000D1080020110800190D0000000000000000000000000000000020000F38080000D1080020110800190D000000000000000000000000000000020000F38080000D1080020110800190D000000000000000000000000000
但此字符串不起作用(187个字符):

错误: 索引和长度必须引用字符串中的位置。 参数名称:长度

public static string CreateCRCCode(string Value)
{
    return Enumerable.Range(0, Value.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToInt32(Value.Substring(x, 2), 16))
                     .Aggregate((i, i1) => i ^ i1)
                     .ToString("X");
}

如何使用超过186个字符的字符串?

根本原因

真正的问题不在于
186个
187个
字符,问题在于
奇数和
偶数
,我想说的是,输入
200个
也会出现同样的错误。原因是,

  • 考虑到Value=“200”所以,
    Value.Length=3
    ,因此
    可枚举范围(0,Value.Length)
    将为您提供
    0,1,2
  • 应用
    .Where(x=>x%2==0)
    后,集合变为
    0,2

  • 因此,当应用(
    Value.Substring(x,2)
    )时,它将从索引
    2
    和off length
    2
    (在第二次迭代中)开始搜索子字符串,该子字符串不是有效的索引。这导致了错误

建议的修复方案

  • 我没有理由在给定的代码段中应用
    Where(x=>x%2==0)
    ,如果有必要,请交叉检查条件和场景
  • 根据集合长度更改可枚举范围,如下所示:

    Enumerable.Range(0, Value.Length % 2 == 0 ? Value.Length : Value.Length-1)
    

由于
Value.Substring(x,2)
的原因,对于任何长度为奇数的字符串,此代码都将失败。
Enumerable.Range(0, Value.Length % 2 == 0 ? Value.Length : Value.Length-1)