CDLTools.cpp 1.89 KB
#include "stdafx.h"
#include "CDLTools.h"

bool HexToChar(const unsigned char* hex, int hex_len, unsigned char* char_text)
{
	bool result = true;
	if (hex && hex_len && char_text)
	{
		int char_count = 0;
		for (int index = 0; index < hex_len; ++index)
		{
			char num[3] = { 0 };
			if (hex[index] <= 0x0f)
			{
				char_text[char_count] = '0';
				++char_count;
				sprintf_s(num, "%X", hex[index]);
				char_text[char_count] = num[0];
				++char_count;
			}
			else
			{
				sprintf_s(num, "%2X", hex[index]);
				char_text[char_count] = num[0];
				++char_count;
				char_text[char_count] = num[1];
				++char_count;
			}
		}
	}
	return result;
}

bool CharToHex(const unsigned char* str, unsigned char& hex)
{
	bool result = true;

	unsigned char hex_temp[2] = { 0 }, temp = 0;
	if (str)
	{
		int count = 2;
		do
		{
			char str_temp = tolower(str[count - 1]);
			switch (str_temp)
			{
			case '0':
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9':
			{
				temp = atoi(&str_temp);
				break;
			}
			case 'a':
			{
				temp = 10;
				break;
			}
			case 'b':
			{
				temp = 11;
				break;
			}
			case 'c':
			{
				temp = 12;
				break;
			}
			case 'd':
			{
				temp = 13;
				break;
			}
			case 'e':
			{
				temp = 14;
				break;
			}
			case 'f':
			{
				temp = 15;
				break;
			}
			}
			hex_temp[count - 1] = temp;
			--count;
		} while (count);

		hex = (hex_temp[0] << 4) + hex_temp[1];
	}
	else
	{
		result = false;
	}
	return result;
}

bool StringToHex(const unsigned char* str, int len, unsigned char* hex)
{
	bool result = true;

	int str_index = 0;
	int index = 0;
	while (result && str_index < len)
	{
		result = CharToHex(&str[str_index], hex[index]);
		++index;
		str_index += 2;
	}

	
	/*for (int index = 0, iStrIndex = 0; iStrIndex < iLen; ++index, iStrIndex += 2)
	{
	CharToHex(&pStr[iStrIndex], pHex[index]);
	}*/

	return result;
}