Converting Decimal Integer to Hexadecimal String using C++

I often encounter situations where I want to convert an Integer value to a Hexadecimal value. Now if it was just for storing, it doesnt really matter as internally decimal and hex values are the same. If it was just printing, its again very straightforward. But the problem I have is to convert it into string value (or chars[]) and use them later. I found a simple program to do this. Here it is:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example of program that does int to hex string
//Adapted from http://www.dreamincode.net/forums/showtopic19694.htm
#include<iostream>
#include <stack>

using namespace
std;

string int2hex(unsigned int dec)
{

int
i = 0;
stack <int>remainder;
string hex, temp;
char
hexDigits[] = { "0123456789abcdef" };

if
(dec == 0)
hex = hexDigits[0];

while
(dec != 0)
{

remainder.push(dec % 16);
dec /= 16;
++
i;
}


while
(i != 0)
{

if
(remainder.top() > 15)
{

temp = int2hex(remainder.top());
hex += temp;
}

hex.push_back(hexDigits[remainder.top()]);
remainder.pop();
--
i;
}

return
hex;
}



int
main()
{

unsigned int
dec = 4294967295;
string hex = int2hex(dec);
cout<<"dec = "<<dec<<" and hex = "<<hex.c_str()<<endl;
dec = 123456789;
hex = int2hex(dec);
cout<<"dec = "<<dec<<" and hex = "<<hex.c_str()<<endl;
dec = 100;
hex = int2hex(dec);
cout<<"dec = "<<dec<<" and hex = "<<hex.c_str()<<endl;
dec = 15;
hex = int2hex(dec);
cout<<"dec = "<<dec<<" and hex = "<<hex.c_str()<<endl;
dec = 0;
hex = int2hex(dec);
cout<<"dec = "<<dec<<" and hex = "<<hex.c_str()<<endl;
cout<<endl;
return
0;
}





The output is as follows:

Check out this stream