C#帧校验和计算 [英] C# frame checksum calculation

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

问题描述

Hii guys. I have a problem. Can you help me. There is an article on the elimination. According to this article I can not find Checksum. Here are a few examples and articles;





文章:



2.1框架



每次数据传输都在一帧内完成。每个数据包具有以下结构:

< STX> FL FN FI [DATA]校验和< ETX>

< STX> 1字节(02hex)帧开始

FL 3字节帧长度,当前未使用,填充空白(20hex)

FN 2字节帧编号,当前未使用,填充空白(20hex)

FI 2字节帧标识符,仅用于'E','I','D'和'S'用于1.字节

当前,2。字节总是空白(20hex)

[DATA]应用数据(如果有的话)

校验和2字节校验和

< ETX> 1字节(03hex)帧终止



2.2错误检测和流量控制



为了确保数据完整性,每帧都会传输校验和。该校验和

是通过将来自< stx>的所有传输字节的值相加来计算的。至[DATA](均为
包含),模数100hex。总和除以10hex。对于

商和分部的其余部分,都会添加30hex。结果(ASCII0到?)表示2个字符的校验和。例如,总和3f9hex将产生?9。







示例通讯记录;



HCTS - > LIS< STX> ..... D.BI | 1234ABC5678 | 30500000 |?7< ETX> ---校验码?7

LIS - > HCTS< ACK>

LIS - > HCTS< STX> ..... D.DW | 1234ABC5678 ||| CHOL .... BILI_TOT | 5 =< ETX> ---校验码5 =

HCTS - > LIS:< ACK>



HCTS - > LIS< STX> ..... D.BI | 1234ABC5678 | D050000F | 1>< ETX> -----校验和1>

LIS - > HCTS< ACK>

HCTS - > LIS< STX> ..... D.BI | 9555907034 | A000000B |; 7< ETX> ------ Checksum; 7

HCTS - > LIS< STX> ..... D.BI || A000000Z |< 0< ETX> -------校验和< 0



不:..... =空白



我没有计算校验和。我在哪里犯错误。



我尝试过:





Articles:

2.1 Framing

Each data transfer takes place within a frame. Each data packet has the following structure:
<STX> FL FN FI [DATA] Checksum <ETX>
<STX> 1 Byte (02hex) Start of frame
FL 3 Byte Frame length, not used currently, filled with blanks (20hex)
FN 2 Byte Frame number, not used currently, filled with blanks (20hex)
FI 2 Byte Frame identifier, only ‘E’, ‘I’, ‘D’ and ‘S’ used for 1. Byte
currently, 2. Byte always blank (20hex)
[DATA] Application data (if present)
Checksum 2 Byte Checksum
<ETX> 1 Byte (03hex) Frame termination

2.2 Error detection and flow control

In order to ensure data integrity, a checksum is transmitted with each frame. This checksum
is calculated by adding the values of all transferred bytes from <stx> to [DATA] (both
inclusive), modulus 100hex. The sum is devided by 10hex. 30hex is added to both the
quotient and the remainder of the division. The results (ASCII ‘0’ to ‘?’) represent the 2- character checksum. For example, the sum 3f9hex will result in "?9".



Sample Communication Log;

HCTS -> LIS <STX>.....D.BI|1234ABC5678|30500000|?7<ETX> --- Checksum ?7
LIS -> HCTS <ACK>
LIS -> HCTS <STX>.....D.DW|1234ABC5678|||CHOL....BILI_TOT|5=<ETX> --- Checksum 5=
HCTS -> LIS: <ACK>

HCTS -> LIS <STX>.....D.BI|1234ABC5678|D050000F|1><ETX> -----Checksum 1>
LIS -> HCTS <ACK>
HCTS -> LIS <STX>.....D.BI|9555907034|A000000B|;7<ETX> ------Checksum ;7
HCTS -> LIS <STX>.....D.BI||A000000Z|<0<ETX> ------- Checksum <0

Not: ..... = blank

I did not calculate the Checksum. Where am i making mistakes.

What I have tried:

public string ConvertToHex(string asciiString)
       {
           string hex = "";
           foreach (char c in asciiString)
           {
               int tmp = c;
               hex += string.Format("{0:X2}", Convert.ToUInt32(tmp.ToString()));
           }
           return hex;
       }







public static byte[] StringToByteArray(string text)
       {
           return Enumerable.Range(0, text.Length)
                            .Where(x => x % 2 == 0)
                            .Select(x => Convert.ToByte(text.Substring(x, 2), 16))
                            .ToArray();
       }







private void button2_Click(object sender, EventArgs e)
       {         
           string hex = ConvertToHex(dataBox.Text);
           int total = StringToByteArray(hex).Sum(x => x);
           string totalStr = string.Format("{0:x}", total);
           resultBox.Text = totalStr;
       }

推荐答案

public static byte [] chk( byte [] buffer)
{
  int sum = 0;
  foreach ( var b in buffer)
    sum += b;
  sum %= 0x100;
  byte [] ch = new byte[2];
  ch[0] = (byte) ((sum >> 4) + 0x30);
  ch[1] = (byte) ((sum & 0xF) + 0x30);
  return ch;
}


// Full data : <STX>     D BI|1234ABC5678|30500000|?7<ETX>

// Data to be calculated = <STX>     D BI|1234ABC5678|30500000|

// Result = ?7




public string ConvertToHex(string asciiString)
       {
           string hex = "";
           foreach (char c in asciiString)
           {
               int tmp = c;
               hex += string.Format("{0:X2}", Convert.ToUInt32(tmp.ToString()));
           }
           return hex;
       }




public static byte[] StringToByteArray(string text)
       {
           return Enumerable.Range(0, text.Length)
                            .Where(x => x % 2 == 0)
                            .Select(x => Convert.ToByte(text.Substring(x, 2), 16))
                            .ToArray();
       }




private static string Csum(string data)
       {
           int total = StringToByteArray(data).Sum(x => x);
           total %= 0x100;
           string totalStr = string.Format("{0:x2}", total);
           int hexa = int.Parse(totalStr.Substring(0, 1), NumberStyles.HexNumber) + 0x30;
           int hexb = int.Parse(totalStr.Substring(1, 1), NumberStyles.HexNumber) + 0x30;
           char a = (char)hexa, b = (char)hexb;
           data = a + b.ToString();
           return data;
       }




private void button2_Click(object sender, EventArgs e)
      {
          try
          {
              string hexstring = "02" + ConvertToHex(dataBox.Text.Replace("<STX>", ""));            
              sumBox.Text = Csum(hexstring);
          }
          catch (Exception)
          {
              sumBox.Text = "??";
          }
      }


private string Pruefsumme(string buffer)

{

int i;

int sum;

sum = 256;

for(i = 0; i< buffer.Length; i ++ )

{

sum - = buffer [i];

if(sum< 0)

{

总和+ = 256;

}

}

Pruefsumme_a1 =(sum& 0xF0)>> ; 4;

a2 = sum& 0x0F;

Pruefsumme_Hex = StringFunctions.ChangeCharacter(Pruefsumme_Hex,0,ASCII [Pruefsumme_a1]);

Pruefsumme_Hex = StringFunctions.ChangeCharacter(Pruefsumme_Hex,1,ASCII [a2]);

Pruefsumme_Hex = Pruefsumme_Hex.Substring(0,2);

return(Pruefsumme_Hex);

}

< br $>


内部静态类StringFunctions

{



public static string ChangeCharacter(string sourceString,int charIndex,char newChar)

{

return(charIndex> 0?sourceString.Substring(0,charIndex):)

+ newChar.ToString()+(charIndex< sourceString.Length - 1?sourceString.Substring(charIndex + 1):);

}



public static bool IsXDigit(char character)

{

if(char.IsDigit(character))

返回true;

else if(ABCDEFabcdef.IndexOf(character)> -1)

返回true;

else

返回false;

}





public static string StrChr(string stringToSearch,char charToFind)

{

int index = stringToSearch。 IndexOf(charToFind);

if(index> -1)

返回stringToSearch.Substring(index);

else

返回null;

}





public static string StrRChr(string stringToSearch,char charToFind )

{

int index = stringToSearch.LastIndexOf(charToFind);

if(index> -1)

返回stringToSearch.Substring(index);

else

r eturn null;

}





public static string StrStr(string stringToSearch,string stringToFind)

{

int index = stringToSearch.IndexOf(stringToFind);

if(index> -1)

返回stringToSearch.Substring(index);

else

返回null;

}



私有静态字符串activeString;

private static int activePosition;

public static string StrTok(string stringToTokenize,string delimiters )

{

if(stringToTokenize!= null)

{

activeString = stringToTokenize;

activePosition = -1;

}





if(activeString == null)

返回null;



if(activePosition == activeString.Length)

返回null;



activePosition ++;

while(acti vePosition< activeString.Length&& delimiters.IndexOf(activeString [activePosition])> -1)

{

activePosition ++;

}



if(activePosition == activeString.Length)

返回null;



int startingPosition = activePosition;

do

{

activePosition ++;

} while(activePosition< activeString.Length&& delimiters.IndexOf(activeString [activePosition])== -1 );



返回activeString.Substring(startingPosition,activePosition - startingPosition);

}



}
private string Pruefsumme(string buffer)
{
int i;
int sum;
sum = 256;
for (i = 0; i < buffer.Length; i++)
{
sum -= buffer[i];
if (sum < 0)
{
sum += 256;
}
}
Pruefsumme_a1 = (sum & 0xF0) >> 4;
a2 = sum & 0x0F;
Pruefsumme_Hex = StringFunctions.ChangeCharacter(Pruefsumme_Hex, 0, ASCII[Pruefsumme_a1]);
Pruefsumme_Hex = StringFunctions.ChangeCharacter(Pruefsumme_Hex, 1, ASCII[a2]);
Pruefsumme_Hex = Pruefsumme_Hex.Substring(0, 2);
return (Pruefsumme_Hex);
}


internal static class StringFunctions
{

public static string ChangeCharacter(string sourceString, int charIndex, char newChar)
{
return (charIndex > 0 ? sourceString.Substring(0, charIndex) : "")
+ newChar.ToString() + (charIndex < sourceString.Length - 1 ? sourceString.Substring(charIndex + 1) : "");
}

public static bool IsXDigit(char character)
{
if (char.IsDigit(character))
return true;
else if ("ABCDEFabcdef".IndexOf(character) > -1)
return true;
else
return false;
}


public static string StrChr(string stringToSearch, char charToFind)
{
int index = stringToSearch.IndexOf(charToFind);
if (index > -1)
return stringToSearch.Substring(index);
else
return null;
}


public static string StrRChr(string stringToSearch, char charToFind)
{
int index = stringToSearch.LastIndexOf(charToFind);
if (index > -1)
return stringToSearch.Substring(index);
else
return null;
}


public static string StrStr(string stringToSearch, string stringToFind)
{
int index = stringToSearch.IndexOf(stringToFind);
if (index > -1)
return stringToSearch.Substring(index);
else
return null;
}

private static string activeString;
private static int activePosition;
public static string StrTok(string stringToTokenize, string delimiters)
{
if (stringToTokenize != null)
{
activeString = stringToTokenize;
activePosition = -1;
}


if (activeString == null)
return null;

if (activePosition == activeString.Length)
return null;

activePosition++;
while (activePosition < activeString.Length && delimiters.IndexOf(activeString[activePosition]) > -1)
{
activePosition++;
}

if (activePosition == activeString.Length)
return null;

int startingPosition = activePosition;
do
{
activePosition++;
} while (activePosition < activeString.Length && delimiters.IndexOf(activeString[activePosition]) == -1);

return activeString.Substring(startingPosition, activePosition - startingPosition);
}

}


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

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