admin 管理员组文章数量: 887031
C++ 基础类型转换(string, wstring,int, hex)
在项目中经常会用到类型间的相互转换,一段时间不用又会忘记,现记录一下方便后面查找。有需要的童鞋拿走不谢,哇哈哈哈....
1、string转wstring
std::wstring s2ws(const std::string& s) {setlocale(LC_ALL, "chs");size_t _dsize = s.size() + 1;wchar_t* _dest = new wchar_t[_dsize];wmemset(_dest, 0, _dsize);const char* _source = s.c_str();mbstowcs(_dest, _source, _dsize);std::wstring result = _dest;delete[] _dest;setlocale(LC_ALL, "C");return result;
}
2、wstring转string
std::string ws2s(const std::wstring& ws) {std::string cur_locale = setlocale(LC_ALL, nullptr);setlocale(LC_ALL, "chs");size_t _dsize = 2 * ws.size() + 1;char* _dest = new char[_dsize];memset(_dest, 0, _dsize);const wchar_t* _source = ws.c_str();wcstombs(_dest, _source, _dsize);std::string result = _dest;delete[] _dest;setlocale(LC_ALL, cur_locale.c_str());return result;
}
3、char*转hex
void strtohex(const char* str, int slen, char* buff, int len) {assert(slen == len * 2);for (int i = 0; i < len; i++) {char strhex[5] = "0x00";strhex[2] = str[i * 2];strhex[3] = str[i * 2 + 1];buff[i] = (byte)strtol(strhex, NULL, 16);}}
4、unsigned转hex
std::string UintToHex(unsigned int value) {stringstream ioss;ioss << std::hex << value;string temp;ioss >> temp;return temp;}
5、int转hex
std::string IntToHex(int value) {stringstream ioss;ioss << std::hex << value;string temp;ioss >> temp;return temp;}
6、float转char*
char * float2str(float val, int precision, char *buf) {char *cur, *end;sprintf(buf, "%.6f", val);if (precision < 6) {cur = buf + strlen(buf) - 1;end = cur - 6 + precision;while ((cur > end) && (*cur == '0')) {*cur = '\0';cur--;}}return buf;}
7、string转unsigned int
unsigned int string2Uint(string str) {unsigned int result(0);//最大可表示值为4294967296(=2‘32-1)//从字符串首位读取到末位(下标由0到str.size() - 1)for (int i = str.size() - 1; i >= 0; i--){unsigned int temp(0), k = str.size() - i - 1;//判断是否为数字if (isdigit(str[i])){//求出数字与零相对位置temp = str[i] - '0';while (k--)temp *= 10;result += temp;} else//exit(-1);break;}return result;}
本文标签: C 基础类型转换(string wstring int hex)
版权声明:本文标题:C++ 基础类型转换(string, wstring,int, hex) 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/jishu/1724403617h749739.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论