본문 바로가기
MFC

HEX CString to BYTE array

by leo21c 2023. 5. 8.
SMALL

MFC Unicode CString을 BYTE 배열로 리턴하는 함수 예제

HEX string은 "0xab 0x01 0x02 0x03 0xfa 0xFF"와 같이 Space로 구분되어 있을 경우


/// 유니코드 CString
/// strData = _T("0xab 0x01 0x02 0x03 0xfa 0xFF");
/// rt[] = { 253, 1, 2, 3, 250, 255 };
byte* etUsbTestDlg::StringToHex(CString strData)
{
	CString strValue;

	int i = 0; // substring index to extract
	TCHAR chSep = ' ';
	byte rt[1024] = { 0, };
	while (AfxExtractSubString(strValue, strData, i, chSep))
	{
		if (strValue.GetLength() != 0)
		{
			strValue = strValue.Trim();
			int pos = strValue.Find(_T("0x")); //0xFC
			if (pos == -1) break;

			CString value = strValue.Mid(2, strValue.GetLength() - 2);
			value = value.MakeUpper();

			char *pValue = (LPSTR)(LPCTSTR)value;
			//value = _T("AB");
			//pValue[] = { 'A', 0, 'B', 0 };
			byte bValue = 0;
			if (pValue[0] >= 'A')
				bValue = (pValue[0] - 'A' + 10) * 16;
			else
				bValue = pValue[0] * 16;

			if (pValue[2] >= 'A')
				bValue += (pValue[2] - 'A' + 10);
			else
				bValue += pValue[2];

			rt[i] = bValue;
		}
		i++;
	}

	return rt;
}

MFC의 AfxExtractSubString 함수를 이용하서 Space Split을 처리하고 각각의 단어를 구분해서 Hex 값을 구하는 간단한 예제 함수.

LIST