• CString 转 unsigned int ;int 转16进制CString


    CString 转 unsigned int

    unsigned long out_word=0;
    CString str;
    
    //GetDlgItemText(IDC_EDIT_DOWORD, str);
    
    • 1
    • 2
    • 3
    • 4

    1、多字节字符集ANSI

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

    2、用Unicode字符集

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

    int 转16进制CString

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

    #include 
    #include 
    
    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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

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

    #include 
    #include 
    
    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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

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

    #include 
    #include 
    #include 
    
    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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
  • 相关阅读:
    探秘三维地形瓦片服务:流畅展现全球地貌的秘密揭秘
    动态链接库搜索顺序
    c++后端开发-学习汇总
    【机器学习】数据均衡学习笔记
    SpringSecurity 全部
    java-锁
    【人工智能】机器学习中的决策树
    Maven找不到依赖终极解决方案
    clang入门大全以及clang全家桶介绍
    DB2中的函数总结归纳
  • 原文地址:https://blog.csdn.net/weixin_43494116/article/details/132743162