//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:
Hi Zahid, can you please tell me if I just want to print out in hex but store it as normal Integer how is it possible. I am not a programmer so if you can write a small subroutine that will be helpful for me, thanks.
ReplyDeleteHi Binny,
ReplyDeleteYou have to write 'hex' before printing the integer value.
cout^^hex^^x^^endl;
Google comments are not allowing to use the less than sign so replace ^ by less than sign. Here x is an integer value but the output will be in hex.
Is this what you asked for?
There's a wikipedia article for this:
ReplyDeletehttp://www.google.com/url?sa=t&source=web&cd=1&ved=0CBUQFjAA&url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FRube_Goldberg_machine&ei=81ENTP6HAcH68Abg6aiNBw&usg=AFQjCNHvpHptYG6PP7ZoznO4vA2-D3cdrQ