例如:定义一个CString a
若a="12345678"
如何把a变成0x78,0x56,0x34,0x12之后用于通信
若a="12345678"
如何把a变成0x78,0x56,0x34,0x12之后用于通信
解决方案 »
- 应用程序与服务器DCOM的TCP连接问题
- CButtonST按钮设置菜单,并使菜单项变灰。
- 小虾VC请教
- 为什么我的一个以前可以编译的程序现在报这个错误呀?请高手指点!!!
- 这个鼠标钩子该怎么办?
- 如果你也碰到过,请留下相关公司名称,及老总名称——程序员黑名单
- 我用atl wizzard写个com,其中的接口函数,字符串参数一定要用BSTR吗,能不能用char数组或string?
- 使用Ms flexgrid,如何实现双击某一行就弹出这一列数据?
- 如何设置才可以使自定义协议不缓存到本地??
- 递归与普通循环相比有哪些优点,缺点?
- CDateTimeCtrl的问题
- 异步读写串口,为何我的线程不向下运行
{
// 做你该做的事;}
char* buf = &n;
buf的字节顺序就是你要求的顺序如果a中包含16进制数据,则用strtol
//注意输出缓冲的大小需要足够大
void initstr(BYTE* inbuf,BYTE* outbuf, int number)
{
BYTE *p;
char c[10];
p=outbuf;
for(int i=0;i<number;)
{
_itoa((unsigned int)(*inbuf++), c, 16);
if(c[1] == 0)
{
*p++='0';
*p++=c[0];
}
else
{
*p++=c[0];
*p++=c[1];
}
*p++=0x20; //空格
i++;
if(i%20==0)
{
*p++=0x0d;
*p++=0x0a;
}
}
}参考一下上面的程序,自己写一个吧
可以转化为 CSting 型的“78563412”但不知道怎样再把它围化为:0x78,0x56,0x34,0x12
不好意思,还望不嫌烦
字节序转换有专门的函数:
htons host data type to network short
htonl host . to network long
ntohl network . to host long
ntohs network . to host short
CString szMid;
int buf[4];
int j=0;
for(int i = a.GetLength();i>0;i-=2){
szMid=a.Mid(i-2,2);
sscanf(szMid.GetBuffer(0),"%x",&buf[j]);
j++;
}
szMid.Format("0x%x,0x%x,0x%x,0x%x\n",buf[0],buf[1],buf[2],buf[3]);
MessageBox(szMid);
CString str = _T("a12345678");
BYTE buf[256] = "\0";int lenght = str.GetLength ();
str.MakeLower();if(lenght%2)//双字节对齐
{
str.Insert(0,"0");
lenght++;
}int index = 0;while (index <= lenght/2)
{
if (str[index] >= '0' && str[index] <= '9'
|| str[index] >= 'A' && str[index] <= 'F')
{
int iVal = 0;
sscanf((LPCSTR)(str.Mid(lenght-(index+1)*2,2)),"%x",&iVal);
buf[index] = (BYTE)iVal;
}
index++;
}
但我的问题是:如何把CString a="12345678"转化为b[]={0x12,0x34,0x56,0x78}
完了,这下肯定没人理我了,但我真的被自己搞晕头了,所以转来转去就转不出来还望各位多多原谅
第二点,麻烦你说明清楚一点:
是要把字符串CString a = "12345678" =>CString b = "0x12,0x34,0x56,0x78";
或是要把字符串CString a = "12345678" =>char b[] = {0x12,0x34,0x56,0x78};
msdn里面有截取字符串的一部分的函数的用法
而且也没有猜明白
我要的是:把字符串CString a = "12345678" =>char b[] = {0x12,0x34,0x56,0x78}
更不明白了,有这样的数组表示吗?
继续关注!
哦,是把字符串CString a = "12345678" =>int b[] = {0x12,0x34,0x56,0x78}
还是char *b[] = {0x12,0x34,0x56,0x78}?
楼主,我被你彻底搞崩溃了,不再关注了,闪人
int nX;//得到的10进制的int
nX = nX/10*16 + nX%10;
nX即是
unsign char buf[256] = "\0";
int index = 0;while (index <= lenght/2)
{
int iVal = 0;
sscanf((LPCSTR)(str.Mid(index*2,2)),"%x",&iVal);
buf[index++] = (BYTE)iVal;
}现在buf的内容为b = {0x12,0x34,0x56,0x78}
如果是数组:
CString a = "12345678";
int n=atoi(a);
char* buf = &n;
int b[4]
char c[4];
for(i=0;i<4;i++){
b[i] = *buf;
c[i] = *buf;
++buf;
}
int b[10];
b[0] = atoi(a.left(2));// b[0] = 12 ,but not 0x12
//then ,how to convert 12 to 0x12?int c[10];
c[0] = b[0]/100 * 256 + b[0]/10 * 16 + b[0]%10; //c[0]的值应该是0X12了,是十进制表示的,应该是你要的了吧
(可是个人感觉这样做好变态)
char* p;
int n=strtol(a, &p, 16);
char* buf = &n;
int b[4]
char c[4];
for(i=0;i<4;i++){
b[i] = *buf;
c[i] = *buf;
++buf;
}数组b即为所求