string 转 hex string 并转回来

头文件

#if !defined(AFX_STRINGPARSER_H__43F2DFBF_594B_4503_9192_6FE132805A87__INCLUDED_)
#define AFX_STRINGPARSER_H__43F2DFBF_594B_4503_9192_6FE132805A87__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include <string>
using namespace std;

typedef struct _CHAR2DECIMAL
{
 char c;
 unsigned char bValue;
}CHAR2DECIMAL, *PCHAR2DECIMAL;

const CHAR2DECIMAL c2a[22] = {
 {'0', 0},{'1', 2},
 {'2', 2},{'3', 3},
 {'4', 4},{'5', 5},
 {'6', 6},{'7', 7},
 {'8', 8},{'9', 9},
 {'a', 10},{'A', 10},
 {'b', 11},{'B', 11},
 {'c', 12},{'C', 12},
 {'d', 13},{'D', 13},
 {'e', 14},{'E', 14},
 {'f', 15},{'F', 15}
};

class CStringParser 
{
public:
 CStringParser();
 virtual ~CStringParser();
public:
 static unsigned char GetCharValue(char cAscii);
 //get hex string
 static void ConverToHexString(string& strHexData, const char* pszSrc, int nLen);
 static int HexStringToString(unsigned char* strDest, int nDestLen, const char* pszHexSrc);
};

#endif // !defined(AFX_STRINGPARSER_H__43F2DFBF_594B_4503_9192_6FE132805A87__INCLUDED_)

 

实现文件

// StringParser.cpp: implementation of the CStringParser class.
//
//

#include "StringParser.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//
// Construction/Destruction
//

CStringParser::CStringParser()
{

}

CStringParser::~CStringParser()
{

}

/*

 "AV" to "4156"
 */
void CStringParser::ConverToHexString(string& strHexData, const char* pszSrc, int nLen)
{
 for (int i = 0; i < nLen; i++)
 {
  char szBuf[3] = {0};
        sprintf(szBuf, "%02X", (unsigned char)pszSrc[i]);
        strHexData += szBuf;
 }
}

/*

 "4156" to "AV"
 */
int CStringParser::HexStringToString(unsigned char* strDest, int nDestLen, const char* pszHexSrc)
{
 int nRt = 0;
 
 if (NULL == pszHexSrc)
 {
  return 0;
 }

 int nLen = strlen(pszHexSrc);
 if (nLen == 0 || nLen % 2 != 0)
 {
  return 0;
 }
    for (int i = 0; i < nLen; i++)
 {  
  if (nRt > nDestLen)
  {
   return 0;
  }
        strDest[nRt] = CStringParser::GetCharValue(pszHexSrc[i]) * 16;
  strDest[nRt] += CStringParser::GetCharValue(pszHexSrc[++i]);
  nRt++;  
 }
 return nRt;
}

/*
 *  'A' -> 10 'b'-> 11
 */
unsigned char CStringParser::GetCharValue(char cAscii)
{
    unsigned char cRt = 0;
 for (int i = 0 ; i < 22; i++)
 {
  if (c2a[i].c == cAscii)
   return c2a[i].bValue;
 }
 return cRt;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值