CString类型与unsigned char类型的相互转换

很好的代码:

CString类型的数据转化为unsigned char类型的数组

CString s1 = "ffffffffffff";
 char *s2 = (char *)(LPCTSTR)s1;
 int nLen = strlen(s2);
 int i = 0;
 char s3[3] = {0};
 while(i < nLen)
 {
  strncpy(s3, s2+i, 2);
  i+= 2;
  int n1 = 1;
  sscanf(s3, "%02X", &n1);
  unsigned char c1 = n1; // 此处得到unsigned char类型, 如果需要数组自己处理
  printf("0x%02x,", c1);
 }

或者
C/C++ code
?
1
2
#include <stdio.h>
#include <tchar.h>

unsigned char [] 转为 CString
C/C++ code
?
1
2
3
4
5
6
7
8
9
unsigned char temp[] = { 0x01, 0xC2, 0x24, 0x80, 0x32, 0x00, 0x00, 0x19, 0x00, 0x00 };
TCHAR sz[2] = { 0 };
CString str;   
for (int i = 0; i < sizeof(temp) / sizeof(temp[0]); i++)
{
    _stprintf(sz, TEXT("%02X"), temp[i]);
    str += sz;
}
cout << str << endl;


CString 转为 unsigned char []
C/C++ code
?
1
2
3
4
5
6
7
8
9
10
11
CString str = "01C22480320000190000";
unsigned char temp2[10];
TCHAR sz2[3] = { 0 };
int nLen = str.GetLength() / 2;
for (int j = 0; j < nLen; j++)
{
    sz2[0] = str[j * 2];
    sz2[1] = str[j * 2 + 1];
 
    _stscanf(sz2, TEXT("%2X"), &temp2[j]);
}

原文地址:http://zhidao.baidu.com/link?url=xoAHOGdFwTznso8ELly3dj7ghUC267pPaqbQvZOwuaBrRWGmC9bk1KFE017LgT9p50Yiwgf07_DfF_I9WPPrDq
原文地址:http://bbs.csdn.net/topics/360021976

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值