最近项目中遇到了字符串转十六进制数据,看了不少别人的代码,也查阅了ASCII对照表。附上ASCII码表如下:

其中用到的代码如下:
如果是CString类转成十六进制可以这样:

void CStringtoHex(CString str, BYTE *SendBuf, int *SendLen)
{
	//CString 转 BYTE型
	int i = 0;
	BYTE GetData[256] = { 0 };
	int GetLen = 0;

	GetLen = str.GetLength();
	for (i = 0; i<GetLen; i++)
	{
		GetData[i] = (BYTE)str.GetBuffer()[i];
	}

	//BYTE转16进制数据 
	int a = 0;
	char temp; //接收字符,用来判断是否为空格,若是则跳过
	char temp1, temp2; //接收一个字节的两个字符 例如EB,则temp1='E',temp2 = 'B'
	
	for (i = 0; i < GetLen; i++)
	{
		temp = GetData[i];
		if (temp == ' ')
			continue;
		if (a == 0)
			temp1 = GetData[i];
		if (a == 1)
			temp2 = GetData[i];
		a++;

		if (a == 2)
		{
			a = 0;
			temp1 = temp1 - '0';
			if (temp1 > 10)
				temp1 = temp1 - 7;
			temp2 = temp2 - '0';
			if (temp2 > 10)
				temp2 = temp2 - 7;

			SendBuf[*SendLen] = temp1 * 16 + temp2;
			(*SendLen)++;  //输出的16进制字符串长度
		}
	}

}

串口端直接发送就行:

unsigned char SendBuf[128] = { 0 };
int SendLen = 0;
CString temp = "";
GetDlgItemText(IDC_CHUAN_EDIT, temp);
if (strcmp("", temp) == 0)
		return;
CStringtoHex(temp, SendBuf, &SendLen);
m_serialport.WriteToPort(SendBuf, SendLen);     //发送十六进制数据
//由于unsigned char和BYTE是一样的,所以直接发送就行,在serailport类中不支持发送BYTE型数据,所以定义数据类型是定义成unsigned char型。

更多推荐

字符转十六进制数据(串口,网口发送)以及ASCII码对照表