# Problem with converting Decimal number to Hexadecimal number

Page 1 of 1

## 12 Replies - 13192 Views - Last Post: 31 January 2010 - 02:58 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=152630&amp;s=974f5014877b24526dd7bf4eb77b5ecd&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 forurup

Reputation: 0
• Posts: 5
• Joined: 24-January 10

# Problem with converting Decimal number to Hexadecimal number

Posted 28 January 2010 - 11:46 PM

hay
I am trying to write code for converting Decimal number to Hexadecimal number by using Recursion n I successfully did it.
But my out was printing more than once.
For example:
Enter Decimal Number :590

but the output should be 24E,i dont understand why it was printing more then once
can an one help me
this is my code
```#include <iostream>
using namespace std;
//function to convert
void main()
{
int decNum,decNumRem[50]; //i took decNumRem to hold remainder
cout << endl << "Convert Decimal Number to Hexadecimal Number";
cout << endl << "Ender Decimal Number:";
cin >> decNum;
cout << endl << "Hexadecimal Number:";
cout << endl;
system("PAUSE");

}

int i=0;
{
if(decNum > 0)
{
r[i]=decNum%16;
i++;
decNum = decNum/16;
}
for(int x=(i-1); x>=0;--x)
{
if(r[x] > 9)
{
switch (r[x])
{
case 10 :
{
cout << "A";
break;
}
case 11 :
{
cout << "B";
break;
}
case 12 :{
cout << "C";
break;
}
case 13 :
{
cout << "D";
break;
}
case 14 :
{
cout << "E";
break;
}
case 15 :
{
cout << "F";
break;
}
}
}
else
{
cout << r[x];
}
}
}

```

hope some one will help .... :-)

This post has been edited by forurup: 29 January 2010 - 12:07 AM

Is This A Good Question/Topic? 0

## Replies To: Problem with converting Decimal number to Hexadecimal number

### #2 David W

• DIC supporter

Reputation: 284
• Posts: 1,798
• Joined: 20-September 08

## Re: Problem with converting Decimal number to Hexadecimal number

Posted 29 January 2010 - 06:15 AM

You might like to try something like this ...

```#include <iostream>

using namespace std;

typedef long long unsigned LLU;

//function to convert ...
void conv_dec_to_hex( int, LLU, int[] );

int find_size( int h[] );

bool more();

const char hexchars[] = "0123456789ABCDEF";

int main()
{
cout << "Convert Decimal Number to Hexadecimal Number ...\n\n";
do
{
cout << "Enter Decimal Number : ";
LLU dec =0 ;
cin >> dec;
cin.clear();
cin.sync();

int i = 0;
int hex[32] = {0}; // hex holds array of int's in range 0..15
conv_dec_to_hex( i, dec, hex );

cout << endl << "Hexadecimal Number: ";

int size = find_size( hex );
for( int j=size-1; j>=0; --j )
cout << hexchars[hex[j]];
cout << endl;

}while( more() );

/*
cout << "\nsize = " << size << endl;

for( int j=0; j<32; ++j )
cout << hex[j] << " ";
*/

}

void conv_dec_to_hex( int i, LLU d, int h[] )
{
if(d > 0)
{
h[i] = d%16;
++i;
d = d/16;
conv_dec_to_hex( i, d, h );
}
}

int find_size( int h[] )
{
int n = 32-1;
while( h[n] == 0 ) --n;
return n+1;
}

bool more() // defaluts to Yes ...
{
cout << "More ... (y/n) ? " << flush;
cin.sync();
}

```

This post has been edited by David W: 29 January 2010 - 06:20 AM

### #3 dave007

Reputation: 9
• Posts: 49
• Joined: 24-January 10

## Re: Problem with converting Decimal number to Hexadecimal number

Posted 29 January 2010 - 09:12 AM

Quote

Try this. The better version your sample code, it does not even require the array.

```#include <iostream>

using namespace std;

void dec_to_hex(int dec_no);

int main()
{
int dec_no;

cout << "Enter decimal number: ";
cin >> dec_no;

dec_to_hex(dec_no);

return 0;
}

void dec_to_hex(int dec_no)
{
int h;

if (dec_no == 0)
{
return;
}

h = dec_no % 16;
dec_no = dec_no / 16;

dec_to_hex(dec_no);  //recursion call

if (h >= 10)
{
cout << char(h + 55);	 //print A-F for 10-15 numbers
}
else
{
cout << h;	   //print number 1-9
}
}

```

hope it will help..

### #4 David W

• DIC supporter

Reputation: 284
• Posts: 1,798
• Joined: 20-September 08

## Re: Problem with converting Decimal number to Hexadecimal number

Posted 29 January 2010 - 03:26 PM

dave007, on 29 Jan, 2010 - 08:12 AM, said:

Try this ... it does not even require the array.

Yes ... much cleaner and better. Thanks for posting that neat code.

### #5 David W

• DIC supporter

Reputation: 284
• Posts: 1,798
• Joined: 20-September 08

## Re: Problem with converting Decimal number to Hexadecimal number

Posted 29 January 2010 - 04:30 PM

so ..as per 007's neat code above ... if you would prefer to construct a hex string ... (to output at some time later) ... you could get that like this:

Note: you may still want to handle the special case of converting the decimal number 0 to the hex string ... "0"

You could use something like this:

```	if( dec_no != 0 ) dec_to_hex(dec_no, hex);
else hex = "0";

```

```#include <iostream>
#include <string>

using namespace std;

void dec_to_hex(int dec_no, string& hex);

int main()
{
int dec_no = 0;

cout << "Enter decimal number: ";
cin >> dec_no;
cin.sync();

string hex;
dec_to_hex(dec_no, hex);

cout << "\nhex = " << hex

<< "\n\nPress 'Enter' to exit ... " << flush;

cin.get();
}

void dec_to_hex(int dec_no, string& hex)
{
int h;

if (dec_no == 0)
{
return;
}

h = dec_no % 16;
dec_no = dec_no / 16;
dec_to_hex(dec_no, hex);  //recursion call

if (h >= 10)
{
//cout << char('A' + h - 10);     //print A-F for 10-15 numbers
hex = hex + char('A' + h - 10);
}
else
{
//cout << h;       //print number 0-9
hex = hex + char('0' + h);
}
}

```

This post has been edited by David W: 29 January 2010 - 04:49 PM

### #6 Aphex19

• Born again Pastafarian.

Reputation: 616
• Posts: 1,873
• Joined: 02-August 09

## Re: Problem with converting Decimal number to Hexadecimal number

Posted 29 January 2010 - 04:51 PM

Im not sure how much this will help people. but I use this for my emulators for debugging purposes.

```//--------------------------------------------------------------------------
// Name: decimalToHex(int decNum)
// Desc: Converts a decimal integer to a hexadecimal LPSTR
//--------------------------------------------------------------------------
LPSTR decimalToHexLPSTR(int decNum)
{
// Get amount of digits in number
std::string decimalStr;
std::stringstream out;
out << decNum;
decimalStr = out.str();
int num_Digits = decimalStr.length();

char *hexChar = (char *)malloc(num_Digits);
char *finalChar = (char *)malloc(num_Digits);

strcpy(hexChar, decimalStr.c_str());
sprintf(finalChar,"%x", atoi(hexChar));
return finalChar;
}
```

It simply takes a decimal number and returns the hex notation

for example.

```char *hexNum = decimalToHexLPSTR(10);
```

### #7 David W

• DIC supporter

Reputation: 284
• Posts: 1,798
• Joined: 20-September 08

## Re: Problem with converting Decimal number to Hexadecimal number

Posted 29 January 2010 - 05:22 PM

Aphex19, on 29 Jan, 2010 - 03:51 PM, said:

Im not sure how much this will help people. but I use this for my emulators for debugging purposes.

```//--------------------------------------------------------------------------
// Name: decimalToHex(int decNum)
// Desc: Converts a decimal integer to a hexadecimal LPSTR
//--------------------------------------------------------------------------
LPSTR decimalToHexLPSTR(int decNum)
{
// Get amount of digits in number
std::string decimalStr;
std::stringstream out;
out << decNum;
decimalStr = out.str();
int num_Digits = decimalStr.length();

char *hexChar = (char *)malloc(num_Digits);
char *finalChar = (char *)malloc(num_Digits);

strcpy(hexChar, decimalStr.c_str());
sprintf(finalChar,"%x", atoi(hexChar));
return finalChar;
}
```

It simply takes a decimal number and returns the hex notation

for example.

```char *hexNum = decimalToHexLPSTR(10);
```

You may need to deal with the memory leak potential above, since you allocate 2 more blocks of new dynamic memory every time you call your function?

This post has been edited by David W: 29 January 2010 - 05:27 PM

### #8 dave007

Reputation: 9
• Posts: 49
• Joined: 24-January 10

## Re: Problem with converting Decimal number to Hexadecimal number

Posted 30 January 2010 - 01:44 AM

Thanks... for making my code better..

### #9 David W

• DIC supporter

Reputation: 284
• Posts: 1,798
• Joined: 20-September 08

## Re: Problem with converting Decimal number to Hexadecimal number

Posted 30 January 2010 - 02:14 AM

dave007, on 30 Jan, 2010 - 12:44 AM, said:

Thanks... for making my code better..

Your clean code IS the kind that I like to see ... and emulate ... especially when I get more sleep : )

Shalom,

David

### #10 forurup

Reputation: 0
• Posts: 5
• Joined: 24-January 10

## Re: Problem with converting Decimal number to Hexadecimal number

Posted 30 January 2010 - 10:51 PM

David W, on 30 Jan, 2010 - 01:14 AM, said:

dave007, on 30 Jan, 2010 - 12:44 AM, said:

Thanks... for making my code better..

Your clean code IS the kind that I like to see ... and emulate ... especially when I get more sleep : )

Shalom,

David

Thank u very much.i used the the code of dva007.
but i did not get whats wrong in my code ...
can anyone correct it .

thank u

### #11 David W

• DIC supporter

Reputation: 284
• Posts: 1,798
• Joined: 20-September 08

## Re: Problem with converting Decimal number to Hexadecimal number

Posted 31 January 2010 - 01:58 AM

forurup, on 30 Jan, 2010 - 09:51 PM, said:

... i did not get whats wrong in my code ... can anyone correct it .

thank u

Here is your code cleaned up some ... and to give the output you want.

```#include <iostream>
using namespace std;

bool more();

int main() // NOTE: *** main returns an int ***
{
int decNum;
do
{
decNum = 0;
cout << "Convert Decimal Number to Hexadecimal Number\n"
<< "Enter Decimal Number: ";
cin >> decNum;
cin.clear(); // in case non-int entered ...
cin.sync();
else cout << "0";
cout << endl << endl;

}while ( more() );
}

bool more() // defaults to yes ...
{
cout << "More y/n ? " << flush;
cin.sync();
}

{
int x;
if(decNum > 0)
{
x = decNum%16;
decNum = decNum /16;
}
if( x > 9 )
{
switch (x)
{
case 10 : cout << "A"; break;
case 11 : cout << "B"; break;
case 12 : cout << "C"; break;
case 13 : cout << "D"; break;
case 14 : cout << "E"; break;
case 15 : cout << "F"; break;
}
}
else
{
cout << x;
}
}

```

### #12 richbria90

Reputation: 1
• Posts: 23
• Joined: 21-January 10

## Re: Problem with converting Decimal number to Hexadecimal number

Posted 31 January 2010 - 02:39 AM

Here is how I did it inside of my class called Convert.. it does the job and is easy to read if you ask me...
btw i have three data members named binNum hexNum and decNum in the class

```void Convert::convDec2Hex(int needsConverted)
{
if(needsConverted>0)
{
if (needsConverted % 16 == 0)
{
convDec2Hex(needsConverted/16);
hexNum = hexNum + "0";
return;
}
else
{
int temp = needsConverted%16;
convDec2Hex(needsConverted/16);
hexSwitch(temp);
}
}
else return;
}

```

The hex switch is long but it just converts the integer given to a string if anyone can come up with something simpilar than my switch I would appreciate it.. my problem is i can't convert the int to string cuz i can't find anything good enough on the interwebs anywhere... im looking for simple i havent used sstream

```void Convert::hexSwitch(int temp)
{
switch(temp)
{
case 1:
hexNum += "1";
break;
case 2:
hexNum += "2";
break;
case 3:
hexNum += "3";
break;
case 4:
hexNum += "4";
break;
case 5:
hexNum += "5";
break;
case 6:
hexNum += "6";
break;
case 7:
hexNum += "7";
break;
case 8:
hexNum += "8";
break;
case 9:
hexNum += "9";
break;
case 10:
hexNum += "A";
break;
case 11:
hexNum += "B";
break;
case 12:
hexNum += "C";
break;
case 13:
hexNum += "D";
break;
case 14:
hexNum += "E";
break;
case 15:
hexNum += "F";
break;
}

```

### #13 David W

• DIC supporter

Reputation: 284
• Posts: 1,798
• Joined: 20-September 08

## Re: Problem with converting Decimal number to Hexadecimal number

Posted 31 January 2010 - 02:58 AM

You might try something like this ...

```
void Convert::hexSwitch(int h)
{
if ( h > 9 )
hexNum += char(h + 'A' -10);     //print A-F for 10-15 numbers
else
hexNum += char(h + '0');       //print number 0 - 9
}

```