drumrboy44
asked on
easiest way to get Decimal to Hex in c++?
if anyone could write a quick code segment or explain the easiest way to convert decimal integers to hex in c++ that'd be great. thanks.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I am assuming you want to do this for display purposes - for any other purpose there is not really a conversion because 0xFF = 255 = 11111111.
Output to the console
printf ( "%x", decimalnumber) ;
save to a string
sprintf ( str, "%x", decimalnumber ) ;
Output to the console
printf ( "%x", decimalnumber) ;
save to a string
sprintf ( str, "%x", decimalnumber ) ;
If your decimal number (and integer) is in a string first convert the number to an int, then format the variable to another string
char pInteger[] = "256"; //my integer string
char pHex[256]; //destination string
int nValue;
if( sscanf( pInteger , "%d" , &nValue ) == 1 ) //returns number of converted elements
{
sprintf( pHex , "0x%08x" , nValue );
}
=> pHex now holds "0x00000100"
CString has a Format() function that doest excactly what sprintf() does, in case you use MFC. Also if your source string is in a CString, you can use it as the first parameter in the sscanf() statement, because CString's can be seen as const char*'s
leave the "0x", and the "08" if you dont want the prefix and the 0-padding and the 8 characters wide field
char pInteger[] = "256"; //my integer string
char pHex[256]; //destination string
int nValue;
if( sscanf( pInteger , "%d" , &nValue ) == 1 ) //returns number of converted elements
{
sprintf( pHex , "0x%08x" , nValue );
}
=> pHex now holds "0x00000100"
CString has a Format() function that doest excactly what sprintf() does, in case you use MFC. Also if your source string is in a CString, you can use it as the first parameter in the sscanf() statement, because CString's can be seen as const char*'s
leave the "0x", and the "08" if you dont want the prefix and the 0-padding and the 8 characters wide field
Just a minor point - if you are going to convert from a string you could also use atoi or atol
char dec[] = "1234" ;
char hex[10] ;
int x ;
x = atoi ( str ) ;
sprintf ( hex, "0x%08x", x ) ; // adopting Ruskialt's formatting options here
char dec[] = "1234" ;
char hex[10] ;
int x ;
x = atoi ( str ) ;
sprintf ( hex, "0x%08x", x ) ; // adopting Ruskialt's formatting options here
http://www.codeproject.com/cpp/baseconvert.asp