Tuesday, 22 September 2009

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:

3 comments:

  1. 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.

    ReplyDelete
  2. Hi Binny,

    You 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?

    ReplyDelete
  3. There's a wikipedia article for this:
    http://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

    ReplyDelete