64,648
社区成员
发帖
与我相关
我的任务
分享
#include "stdafx.h"
#include <string.h>
void AlphaToNum(char * ListChar, unsigned char * ReturnByte, int n)
{
unsigned char High;
unsigned char low;
for(int i = 0; i < n; i+=2)
{
if(ListChar[i] >= '0' && ListChar[i] <= '9')
{
High = ListChar[i] - '0';
}
if(ListChar[i] >= 'a' && ListChar[i] <= 'f')
{
High = ListChar[i] - 'a' + 10;
}
if(ListChar[i] >= 'A' && ListChar[i] <= 'F')
{
High = ListChar[i] - 'A' + 10;
}
if(ListChar[i+1] >= '0' && ListChar[i+1] <= '9')
{
low = ListChar[i+1] - '0';
}
if(ListChar[i+1] >= 'a' && ListChar[i+1] <= 'f')
{
low = ListChar[i+1] - 'a' + 10;
}
if(ListChar[i+1] >= 'A' && ListChar[i+1] <= 'F')
{
low = ListChar[i+1] - 'A' + 10;
}
ReturnByte[i] = High * 16 + low;
}
}
int main(int argc, char* argv[])
{
char * str = "AAAA580020";
int Len = strlen(str);
unsigned char * data = new unsigned char[Len];
AlphaToNum(str, data, Len);
printf("%X", data[0]);
printf("\n");
return 0;
}
for(int i = 0, j = 0; j < ((int)str.size())/2; j += 2, ++i)
{
data[i]= 0;
data[i]= str[j] - '0';
data[i] < <= 4;
data[i] |= str[j + 1] - '0';
}//字符转字节
有些错误,改下
UpdateData(TRUE);
CByteArray arraySend;
arraySend.RemoveAll();
//arraySend.SetSize(10); 10必须为准确字节数,不然其后补0,满10位
BYTE byte[100];
int n = 0;
CString str = m_strSendASCII;
int str_length = str.GetLength();
CString strTemp;
// 用于统计字符串长度
CString str_Box;
str_Box.Format("%d", str_length);
MessageBox(str_Box);
// 字符串转换为 BYTE 类型
// 方式一:sscanf(strTemp, "%02x", &int_temp);
for (int i = 0; i < str_length; )
{
strTemp = str.Mid(i, 2);
//byte[n] = static_cast<BYTE>(atoi(strTemp2.GetBuffer(10)));
int int_temp = 0;
sscanf(strTemp, "%02x", &int_temp);
byte[n] = (BYTE)int_temp;
i += 2;
n++;
strTemp.ReleaseBuffer();
}
for (n = 0; n < str_length / 2; n++)
{
//arraySend.SetAt(n, byte[n]); // arraySend.SetSize(10); 如果发送少于10个字节,那会补0,到10个字节
arraySend.Add(byte[n]);
}
m_MSComm1.SetOutput(COleVariant(arraySend));
}
UpdateData(TRUE); // 从Edit Box获取字符串CString m_strSendASCII
CByteArray arraySend;
CString str = m_strSendASCII;
BYTE data[100];
BYTE temp;
if (str.GetLength() % 2 != 0)
{
MessageBox("输入字符串的字符个数不为偶数,请重新输入");
m_strSendASCII = "";
UpdateData(FALSE);
}
else
{
for(int i = 0; i < str.GetLength(); i += 2)
{
if ((str[i] >= '0') && (str[i] <= '9'))
{
data[i]= str[i] - '0';
}
else if ((str[i] >= 'a') && (str[i] <= 'z'))
{
data[i]= str[i] - 'a' + 10;
}
else if ((str[i] >= 'A') && (str[i] <= 'Z'))
{
data[i]= str[i] - 'A' + 10;
}
else
{
MessageBox("输入错误,请检查,并重新输入");
}
data[i] = data[i] << 4;
if ((str[i + 1] >= '0') && (str[i + 1] <= '9'))
{
temp= str[i + 1] - '0';
}
else if ((str[i + 1] >= 'a') && (str[i + 1] <= 'z'))
{
temp= str[i + 1] - 'a' + 10;
}
else if ((str[i + 1] >= 'A') && (str[i + 1] <= 'Z'))
{
temp= str[i + 1] - 'A' + 10;
}
else
{
MessageBox("输入错误,请检查,并重新输入");
}
data[i] |= temp;
arraySend.Add(data[i]);
}
m_MSComm1.SetOutput(COleVariant(arraySend));
}
}