头文件
#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
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;
}