方法一:
转自:http://hi.baidu.com/jetqu2003/blog/item/fef7f7e98e834739b90e2d15
.html
需求:
16进制字符串CString 如何转为 BYTE[]
CString str ="01 02 03 04";
BYTE cmd[1024];
赋值后
cmd[1024] = {0X01,0X02,0X03,0X04};
第一步:将ASCII码转化为16进制数(注意:ASCII码和16进制数的区别)
//
将ASCII码转化为16进制数
BYTE CSendDataDlg::ConvertHexChar(BYTE ch)
{
if((ch>='0')&&(ch<='9'))
return ch-0x30;
else if((ch>='A')&&(ch<='F'))
return ch-'A'+10;
else if((ch>='a')&&(ch<='f'))
return ch-'a'+10;
else
return -1;
}
第二步:调用上面的那个函数来实现需求
CString str
=
"
01 02 03 04
"
;
BYTE tmpByte
=
0x00
;
int
strLen
=
str.GetLength();
BYTE cmd[
1024
];
memset(cmd,
'
\0
'
,
sizeof
(cmd));
![C++ <wbr>16进制字符串CString <wbr>如何转为 <wbr>BYTE[] <wbr>数组 C++ <wbr>16进制字符串CString <wbr>如何转为 <wbr>BYTE[] <wbr>数组](https://i-blog.csdnimg.cn/blog_migrate/cbef093dcc044b2793832001e2365e43.gif)
for
(
int
i
=
0
, j
=
0
; i
<
1024
,j
<
strLen; i
++
,j
++
)
{
if (str[j] == ' ')
++j;
tmpByte = str[j];
cmd[i] = ConvertHexChar(tmpByte)<<4;//左移4位
if (str[++j] == ' ')
++j;
tmpByte = str[j];
cmd[i] = cmd[i] + (ConvertHexChar(tmpByte) & 0xF);//取低4位然后相加。
}
注释:
把字符赋给BYTE,实则赋的是字符的ASCII码值,因此要先把ASCII码转化为对应的16进制数。
两个字符赋给一个BYTE,就要把第一个字符放到BYTE的高4位,而第二个字符放到BYTE的低4位。
中间通过判断去掉空格。
方法二:
转自:
需求:
16进制字符串CString如何转为BYTE[]数组
CString str ="56 45 52 30 30";
BYTE buf[64];
赋值后
buf[64] = {0X56,0X45,0X52,0X30,0X30};
int CCP210xSerialTestDlg::Str2Hex(CString str, unsigned char *data)
{
unsigned int t;
int Length;
int len=str.GetLength();
char a[10]={0};
Length=0;
for(int i=0; i<len; )
{
if(str[i]==' ') //空格
{
i++;
continue;
}
a[0]=str[i]; // high byte
i++;
if (i>=len)
{
break;
}
a[1]=str[i]; // low byte
a[2]='/0'; // 字符串结束标志
t=strtoul(a,NULL,16); //将字符串转换成无符号长整型数
data[Length]=(unsigned char)t;
Length++;
i++;
}
return Length; //转换的字节数
}
处理这类问题的方法很多,我的方法的特点在于使用了strtoul()函数。
虽然可行,但我还是有疑问,CString类可以直接用数组下标的方式(str[i])访问吗?感觉是不可以这样做,却能解决问题,很纳闷。希望有高手指点一下,不胜感谢。