C++ 类型转换 int, hex,char* float, string, wstring

日常的开发中经常会用到类型的相互转换,这里记录一下;

1, int转hex

std::string IntToHex(int value) {
		stringstream ioss;
		ioss << std::hex << value;
		string temp;
		ioss >> temp;
		return temp;
	}

2, int转hex 设置宽度

std::string intToHexString(int input, int width) const
{
	std::stringstream convert;
	convert << std::hex  << std::setfill('0');
	convert << std::setw(width) << input;
	return convert.str();
}

3,int to string 可设置宽度

// default width = 1
std::string intToString(int input, int width = 1) const;

std::string intToString(int input, int width) const
{
	std::stringstream convert;
	convert << std::dec << std::setfill('0');
	convert << std::setw(width) << input;
	return convert.str();
}

4.string to int

int stringToInt(std::string input) const
{
	int retVal = 0;
	std::stringstream convert(input);
	convert << std::hex;
	convert >> retVal;
	return retVal;
}

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

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

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

8. unsigned转hex

std::string UintToHex(unsigned int value) {
		stringstream ioss;
		ioss << std::hex << value;
		string temp;
		ioss >> temp;
 
		return temp;
	}

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

10. 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/C++,c++,开发语言)