// HexCode.cpp: implementation of the WMHexCode class.
//
//////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000 Robert Cunnings. All rights reserved.
//
// You may copy, modify, distribute or publish this code free of charge.
//
// NO WARRANTY: This software is provided AS IS, without warranty of any kind.
//
//////////////////////////////////////////////////////////////////////
//
// Class used to hex encode and decode binary data.
// 
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "HexCode.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

WMHexCode::WMHexCode()
{
	m_strHexChars = "0123456789ABCDEF";
}

WMHexCode::~WMHexCode()
{

}

bool WMHexCode::Encode(const unsigned char *pszUnencoded, int nLength, string& strEncoded)
{
	for (int i = 0; i < nLength; i++)
	{
		unsigned char c = pszUnencoded[i];
		strEncoded += m_strHexChars[c >> 4];
		strEncoded += m_strHexChars[c & 0x0f];
	}
	// done
	return true;
}

bool WMHexCode::Decode(const string& strEncoded, unsigned char *pszDecoded, int& nOutLength)
{
	// make sure length is a multiple of 2
	if ((strEncoded.size() % 2) > 0)
	{
		// no good
		return false;
	}
	int nLength = (int)strEncoded.size() / 2;
	nOutLength = nLength;
	if (pszDecoded == NULL)
	{
		// no conversion...only a query for output buffer size
		return true;
	}
	// decode
	int j = 0;
	for (int i = 0; i < nLength; i++)
	{
		unsigned char uc;
		string::size_type pos = m_strHexChars.find(toupper(strEncoded[j++]));
		if (pos == string::npos)
		{
			return false;
		}
		uc = ((unsigned char)pos << 4);
		pos = m_strHexChars.find(toupper(strEncoded[j++]));
		if (pos == string::npos)
		{
			return false;
		}
		uc |= (unsigned char)pos;
		pszDecoded[i] = uc;
	}
	// done
	return true;
}

