Link to home
Start Free TrialLog in
Avatar of aderounm
aderounmFlag for United States of America

asked on

Converting decimal to hex and vice-versa

Are there any C++ functions or Windows functions that can be used to convert to hex and vice-versa?

For example if I have a variable whose value is 10 million how would I convert it to the hex equivalent, 989680?? And how would I convert back to decimal? I prefer standard C++ functions but will use windows or MFC functions if there is no other way.
Avatar of jkr
jkr
Flag of Germany image

To hex:

char acHex [ MAX_BUFFER];

int number = 1234;
sprintf ( acHex, "%x", number);

To dec:

3include <stdlib.h>
char* pszHex = "0xab124def";
char* p;
int number;

number = strtol ( pszHex, &pc, 16);
Avatar of AssafLavie
AssafLavie

or, in standard C++ (not c):
{
     ostringstream oss;
     oss << hex << 123;
     cout << oss.str();
     oss.str("");
     oss << dec << 0x7b;
     cout << oss.str();
}
or, if you're just interested in printing:

cout << hex << 123 << dec << 123 << oct << 123;

etc.
I once wrote a helper function to do somclever onterpretation of numbers entered (various hex markers allowed, etc..) see
http://buerger.metropolis.de/bitbucket/controls/moreorless.html#HexDec%20Converter , perhaps it helps yu
Hmm, ich mag besonders den 'Netz gegen Rechts'-Link auf der Hauptseite :o)
If this is the best of the site... well, perhaps I should change my profession ;-)
Nicht 'das beste' - aber es freut mich immer, das zu sehen :o)
Medabrim li begermanit, ah? Walla yofi...

Ya'll start speaking in a manner which everyone can understand, alright?

As an Israeli I find this misterious german dialog suspicious and scary!
(not really... :)

(well, a bit maybe...)
>>As an Israeli I find this misterious german dialog
>>suspicious and scary!

So, to translate it (and take away the scaryness, maybe):

Peter has a 'The Net against Nazis' button/link on his page, and I was just expressing my appreciation for that...
< wheew >
ASKER CERTIFIED SOLUTION
Avatar of noescom
noescom

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Only if you pass it as follows

int i HexToDec("ff",16);

You forgot the radix.

Vin.
#include <stdlib.h>
#include <stdio.h>

// IntToHex:
     int n= 10000000;  // ten million
     char szBuf[20];
     sprintf( szBuf, "%X", n ); // eg, "989680"

// common to add leading 0s so it is eight chars:

     sprintf( szBuf, "%08.8X", n ); // eg, "00989680"

//IntToDec:
     // char szBuf[20];
     sprintf( szBuf, "%d", n ); // eg, "10000000"

//HexToInt:
     char* pEndedHere;
     int m= strtol(szBuf, &pEndedHere, 16);

//DecToInt:
     // char* pEndedHere;
     m= strtol(szBuf, &pEndedHere, 10);

-- Dan