string、int類型數據轉換爲十六進制

1. string 字符串轉換爲十六進制字符串輸出

string strToHex(string str)		//string 轉換爲十六進制
{
	const std::string hex = "0123456789ABCDEF";
	std::stringstream ss;
	for (std::string::size_type i = 0; i < str.size(); ++i)
		ss << hex[(unsigned char)str[i] >> 4] << hex[(unsigned char)str[i] & 0xf] << "";
	return ss.str();
}

2. int型數據轉換爲十六進制字符數組

char* intToHex(int values)
{
	int i = 0;
	char *res = new char[100];
	stack <char> s;
	if (values == 0)
		s.push(values);
	while (values) {
		s.push(values % 16);
		values /= 16;
	}
	while (!s.empty())	 
	{
		switch (s.top())
		{
		case 10:res[i] = 'A'; break;
		case 11:res[i] = 'B'; break;
		case 12:res[i] = 'C'; break;
		case 13:res[i] = 'D'; break;
		case 14:res[i] = 'E'; break;
		case 15:res[i] = 'F'; break;
		default:res[i] = s.top() + '0';  break;
		}
		i++;
		s.pop();
	}
	res[i] = '\0';
/*	if (i == 1)	//針對10以下數據,輸出 00 01 02 03等格式 
	{
		if (res[0] != '0') {
			int temp = i;
			res[i] = res[--temp];
			res[temp] = '0';
			res[++i] = '\0';
		}
		else {
			res[0] = '0';
			res[1] = '0';
			res[2] = '\0';
		}*/
	}
	return res;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章