mfc报文相关算法

1、传入_T("AAAABBBBCC"),返回_T("AA AA BB BB CC")

CString FormatPacket(CString packet_str)
{
  packet_str.Replace(_T(" "),_T(""));
  CString packet_backspace_str;//带空格的包
  CString temp_str;//临时存一个十六进制
  int j = 0;
  /*这里加上空格*/
  for (int i = 0;i<packet_str.GetLength();i++)
    {
    temp_str = packet_str.GetAt(i++);
    temp_str += packet_str.GetAt(i);
    temp_str += _T(" ");
    packet_backspace_str += temp_str;
  }
  return packet_backspace_str;
}

2、传入_T("AAAABBBBCC"),返回_T("AAAABBBBCCXX"),XX是校验和

CString PutCheckByte(CString packet_str,BOOL RESULT4TAX)//
{
  CString temp_str;
  int packet_lenth_int = packet_str.GetLength();
  unsigned short sum =0;
  for(int i=0;i<packet_lenth_int;i++)
    {
    temp_str = packet_str.GetAt(i++);
    temp_str += packet_str.GetAt(i);
    sum += wcstol(temp_str,NULL,16);
    }
  sum = sum % 256;
  CString checksum_result;
  checksum_result.Format(_T("%02x"),sum);
  packet_str += checksum_result;
  return packet_str;//返回的是整个报文

}

3、传入_T("你好123"),返回7,这个字符串实际所占长度

int GetByteLenth(CString unicode_str)
{
  int lenth_int;//字符数,5
  lenth_int = unicode_str.GetLength();
  int result_int = 0;
  for (int i=0;i<lenth_int;i++)
    {
    if((unicode_str.GetAt(i) >= 48 && unicode_str.GetAt(i) <= 57) ||(unicode_str.GetAt(i) >= 65 && unicode_str.GetAt(i) <= 90)||(unicode_str.GetAt(i)     >= 97 && unicode_str.GetAt(i) <= 122))
      result_int += 1;
    else
      result_int += 2;
    }
  return result_int;
}

4、传入字节数组,BYTE array[10],返回带空格CString

CString UChar2CString(BYTE* data_byte,int count)//count代表data_byte的字节数
{
  CString temp_str;
  CString result_str;
  temp_str = _T("");
  result_str = _T("");
  for (int i=0;i<count;i++)
    {
    temp_str.Format(_T("%02x"),data_byte[i]);
    result_str += temp_str;
    result_str += _T(" ");
    }
  result_str = result_str.MakeUpper();
  return result_str;
}

posted @ 2017-02-16 16:22  朱小勇  阅读(376)  评论(0编辑  收藏  举报