#include "stdafx.h"
#include "resource.h"
#include "string2hex.h"
UCHAR BtoH(char);

UCHAR BtoH(char ch)
{
    if ((ch >= '0') && (ch <= '9'))
    {
        return (ch - '0');
    }
    if ((ch >= 'A') && (ch <= 'F'))
    {
        return (ch - 'A' + 0xA);
    }
    if ((ch >= 'a') && (ch <= 'f'))
    {
        return (ch - 'a' + 0xA);
    }
	return '0';
}
//string to hex
int _StrToHex(char *szDest, LPCSTR szSource, int iLength)
{
	BYTE c, temp[2];
	int p=0, i=0, len=0;
	BOOL str=FALSE, skip=FALSE;

	memset(szDest, 0, iLength);

    while (len<iLength)
	{
		c=szSource[i++];
		//switch skip mode
		if(c=='@' && !str)		// @ in string mode treat as normal char
			skip=!skip;

		else if (skip)			// in comment mode, skip any char, including $
			continue;

		// below are in retreive mode

		// switch string format mode
		else if(c=='$')	
			str=!str;				

		// if in string format mode and not string end, save the char directly
		else if(str && c)	
			szDest[len++]=c;

		// below are conditions in hex mode

		// hex value char, translate to number if it's the 2nd char
		else if(IS_HEX(c) )		
		{
			temp[p]=c;
			p=(p+1)%2;			// toggle p;
			if(!p)				// if p=0, new byte is ok
				szDest[len++]=(BtoH(temp[0]) << 4) + BtoH(temp[1]);
			continue;
		}		

		// may be space, other chars, or string end
		if(p)		// if a single char ready to translate
		{
			szDest[len++]=BtoH(temp[0]);
			p=0;	// reset p
		}

		if(!c)
			break;	// if string end, job done
	}
	return len;

  //      *szDest++ = (BtoH(*szSource++) << 4) + BtoH(*szSource++);
}


//hex to string
void _HexToStr(char *pcDest, const char* pcSource, int iLength, char c)
{
	while( iLength-- )
	{
		char chHigh, chLow;
		chHigh = (*pcSource)>>4 &0x0f;
		chLow  = (*pcSource)    &0x0f;
		*pcDest++ = (chHigh < 0x0a) ? ('0'+chHigh):('A'+chHigh-0x0a);
		*pcDest++ = (chLow < 0x0a) ? ('0'+chLow):('A'+chLow -0x0a);
		if(c)
			*pcDest++ = c;
		++pcSource;
	}
}