需要计算字符串的校验和 [英] Need to calsulate the Checksum of a string

查看:99
本文介绍了需要计算字符串的校验和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是要求:

校验和最初设置为零,是在SOH字符之后(但不包括)SET字符和ETX字符(包括ETX字符)之后的所有字符的16位二进制加法(如果适用,不包括奇偶校验).然后将校验和表示为4 ASCII十六进制字符进行传输.

The Checksum is initially set to zero and is the 16-bit binary addition (excluding parity if applicable) of all characters after, but not including, the SOH character and through (and including) the ETX character. The Checksum is then represented as four ASCII-Hex characters for transmission.

我到处搜索并找到以下代码:


private static string GetChecksum(string s)
    {
      int checksum = 0;
      foreach (char c in s)
      {
        checksum += Convert.ToByte(c);
      }
      return checksum.ToString("X4");
    }

推荐答案

您所拥有的例程不排除第一个字符(假定为SOH),并且在您的规范说使用short时,它也使用int.实际上,使用ushort会更好.

The routine you have do not exclude the first character (presumed to be the SOH) from the calculation and also it use an int when your spec say to use a short. In fact a ushort would be better.

此外,如果您直接使用字节字符串而不是字符串,并且该字节字符串包含7位字符的奇偶校验,则可能必须排除它以满足规范要求(用& = 0x7F对其进行屏蔽).

Also if you work directly with a byte string instead of a character string, and that byte string contains parity on 7 bit characters you may have to exclude it to satisfy the spec (masking it with &= 0x7F).

/LM

< Jim Bedson>写在消息新闻中:c88037f3-33da-41b2-8859-d1595c4a7fe6@communitybridge.codeplex.com ...

<Jim Bedson> wrote in message news:c88037f3-33da-41b2-8859-d1595c4a7fe6@communitybridge.codeplex.com...

这是要求:

校验和最初设置为零,是在SOH字符之后(但不包括)SET字符和ETX字符(包括ETX字符)之后的所有字符的16位二进制加法(如果适用,不包括奇偶校验).然后将校验和表示为四个ASCII十六进制 传输字符.
我四处搜索,发现以下代码:

Here is the requirement:

The Checksum is initially set to zero and is the 16-bit binary addition (excluding parity if applicable) of all characters after, but not including, the SOH character and through (and including) the ETX character. The Checksum is then represented as four ASCII-Hex characters for transmission.
I searched around and found the following code:


private static string GetChecksum(string s) { int checksum = 0; foreach (char c in s) { checksum += Convert.ToByte(c); } return checksum.ToString("X4"); }

但是我有两个问题:
1.我不知道在做什么.
2.不能与我要好的包装盒匹配.
如果我用一个好的字符串替换一个可以正常工作的数据包,并通过上面的代码运行它,那么我得到的值将与我期望的值不同.不幸的是,按照行业的性质,我将无法在字符串中包含实际数据.但是我可以这么说 它是可变长度的,包括字母和数字字符.
非常感谢您.
谢谢吉姆

But I have two problems:
1. I don't know what it's doing.
2. It doesn't match what I have for a good packet that works.
If I substitue a good string for a packet that works, and run it through the code above, I get a different value than i'm expecting. Unfortunately, do to the nature of the industry, I wont be able to include the actuall data in the string. But I can say that it is variable length and includes both alpha and numeric charactors.
Any help is very much apprciated.
Thanks Jim

Microsoft Outlook Express 6.00.2900.5931>


这篇关于需要计算字符串的校验和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆