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

编程知识 更新时间:2023-04-04 00:55:43

最近项目中遇到了字符串转十六进制数据,看了不少别人的代码,也查阅了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码对照表

本文发布于:2023-04-04 00:55:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/18ce5c44d3419b09734a584b607bdeb9.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:串口   对照表   字符   数据   转十六进制

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 40410文章数
  • 14阅读数
  • 0评论数