1. 程式人生 > >Hex和ASCII相互轉換函式

Hex和ASCII相互轉換函式

以下兩個函式用於實現十六進位制和ASCII碼值之間的轉換

int Hex2Ascii(char* hex, char* ascii)
{
	int len = strlen(hex), tlen, i, cnt;
	
	for (i = 0, cnt = 0, tlen = 0; i<len; i++)
	{
		char c = toupper(hex[i]);

		if ((c>='0'&& c<='9') || (c>='A'&& c<='F'))
		{
			BYTE t = (c >= 'A') ? c - 'A' + 10 : c - '0';

			if (cnt)
				ascii[tlen++] += t, cnt = 0;
			else
				ascii[tlen] = t << 4, cnt = 1;
		}
	}
	
	return tlen;
}

int Ascii2Hex(char* ascii, char* hex)
{
	int i, len = strlen(ascii);
	char chHex[] = "0123456789ABCDEF";
					
	for (i = 0; i<len; i++)
	{
		hex[i*3]	= chHex[((BYTE)ascii[i]) >> 4];
		hex[i*3 +1]	= chHex[((BYTE)ascii[i]) & 0xf];
		hex[i*3 +2]	= ' ';
	}

	hex[len * 3] = '\0';

	return len * 3;
}
//! 傳送資料