CString 转 unsigned int ;int 转16进制CString

CString 转 unsigned int

unsigned long out_word=0;
CString str;

//GetDlgItemText(IDC_EDIT_DOWORD, str);

1、多字节字符集ANSI

char * chStr;
chStr = (char*)str.GetBuffer(0);//只能用多字节字符集ANSI,用Unicode字符集会报错
out_word = strtoul(chStr, NULL, 10);

2、用Unicode字符集

out_word = _tcstoul(str,NULL,10);//_tstol() 有符号
//用atoi 最高位无法转换,atoi f返回的是int型
//out_word = atoi(str.GetBuffer(0));

int 转16进制CString

在 C++ 中,可以使用 std::ostringstream 将整数转换为十六进制字符串。这需要 头文件。下面是一个示例程序:

#include <iostream>
#include <sstream>

int main() {
    unsigned int i = 1000;
    std::ostringstream ss;
    ss << std::hex << i;
    std::string result = ss.str();
    std::cout << result << std::endl; // 3e8
    //CString strTempData(result.c_str());
    return 0;
}

也可以在十六进制字符串前面加上基数说明符 0x,如下所示:

#include <iostream>
#include <sstream>

int main() {
    unsigned int i = 1000;
    std::ostringstream ss;
    ss << "0x" << std::hex << i;
    std::string result = ss.str();
    std::cout << result << std::endl; // 0x3e8
    //CString strTempData(result.c_str());
    return 0;
}

还可以使用 std::setfill 和 std::setw 函数来填充前导零,这些函数来自 头文件。下面是一个示例程序:

#include <iostream>
#include <sstream>
#include <iomanip>

int main() {
    unsigned int i = 1000;
    std::ostringstream ss;
    ss << "0x" << std::setfill('0') << std::setw(8) << std::hex << i;
    std::string result = ss.str();
    std::cout << result << std::endl; // 0x000003e8
    //CString strTempData(result.c_str());
    return 0;
}

EDIT控件输入16进制数据

unsigned int out_word=0;
CString str;

GetDlgItemText(IDC_EDIT_DOWORD, str);
//	out_word = _tcstoul(str,NULL,10);//str 转 int
//	sscanf(str.GetBuffer(), "%x", &out_word);
//在Unicode版本的MFC中,CString的GetBuffer方法返回的是wchar_t*类型,而不是char*类型。因此,你不能直接将其传递给sscanf函数
char buffer[256]; // 假设输入的字符串长度不会超过256
WideCharToMultiByte(CP_ACP, 0, str, -1, buffer, 256, NULL, NULL);
sscanf(buffer, "%x", &out_word);
//sscanf(buffer, "%d", &out_word);//输入的是10进制
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值