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进制