在 C# 中计算校验和

Calculating a checksum in C#

我正在为 .NET 环境中用 C# 编写的基于快递的系统的清单文件编写校验和。 我需要一个 8 位数的字段来表示校验和,该校验和是按照以下公式计算的:

记录校验和算法 形成

乘积的32位算术和

• 记录中每个ASCII字符的低7位

• 每个字符在记录中的位置,从第一个字符开始编号。 对于记录的长度,但不包括校验和字段本身:

Sum = Σi ASCII(记录中的第i个字符).( i ) 我超出了不包括校验和字段的记录长度。

执行此计算后,将结果和转换为二进制并将32位低位拆分 Sum 的位分为八个 4 位块(八位字节)。请注意,每个八位字节都有一个小数 number 取值范围为 0 到 15.

将ASCII 0(零)的偏移量添加到每个八位字节以形成ASCII 码编号。

将ASCII码数字转换成对应的ASCII字符,从而形成可打印的 0123456789:;<=>?.

范围内的字符

将这些字符中的每一个连接起来形成一个总共八 (8) 个字符的字符串 长度。

我不是最擅长数学的,所以我很难按照文档正确地编写代码。 到目前为止我已经写了以下内容:

byte[] sumOfAscii = null;

for(int i = 1; i< recordCheckSum.Length; i++)
{
    string indexChar = recordCheckSum.ElementAt(i).ToString();
    byte[] asciiChar = Encoding.ASCII.GetBytes(indexChar);

     for(int x = 0; x<asciiChar[6]; x++)
     {
        sumOfAscii += asciiChar[x];
     }
}

     //Turn into octets
    byte firstOctet = 0;
for(int i = 0;i< sumOfAscii[6]; i++)
{
    firstOctet += recordCheckSum;
}

其中 recordCheckSum 是由 deliveryAddresses、产品名称等组成的字符串,不包括 8 位校验和。

在我苦苦挣扎的时候,如果能帮助我计算这个,我将不胜感激。

随着我的进行,有一些笔记在排队。最后还有一些关于计算的注释。

uint sum = 0;
uint zeroOffset = 0x30; // ASCII '0'

byte[] inputData = Encoding.ASCII.GetBytes(recordCheckSum);

for (int i = 0; i < inputData.Length; i++)
{
    int product = inputData[i] & 0x7F; // Take the low 7 bits from the record.
    product *= i + 1; // Multiply by the 1 based position.
    sum += (uint)product; // Add the product to the running sum.
}

byte[] result = new byte[8];
for (int i = 0; i < 8; i++) // if the checksum is reversed, make this:
                            // for (int i = 7; i >=0; i--) 
{
    uint current = (uint)(sum & 0x0f); // take the lowest 4 bits.
    current += zeroOffset; // Add '0'
    result[i] = (byte)current;
    sum = sum >> 4; // Right shift the bottom 4 bits off.
}

string checksum = Encoding.ASCII.GetString(result);

请注意,我使用 &>> 运算符,您可能熟悉也可能不熟悉。 & 运算符是 bitwise and operator. The >> operator is logical shift right