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;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值