Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Display as Hex

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
How do I display a decimal number and the corresponding hexadecimal value?
 
Code:
#include <iostream.h>

const char values[ 20 ] = &quot;0123456789ABCDEF&quot;;

void convertToHex( char *str, int p , int pos )
{    
    int a = p % 16;

    if ( p > 0 )
    {
        str[ pos ] = values[ a ];
        convertToHex( str , p / 16 , pos - 1 );
    }
}

void convertToHex( char *str, int p )
{   
    int a = 0 , b;
    b = p;

    while ( b > 15 )
    {
        b = b / 16;
        a = a + 1;
    }

    str[ a + 1 ] = '\0';
    convertToHex( str , p , a );
}

int main()
{
    int amount;
    char buf[ 80 ] = &quot;&quot;;

    cout << &quot;Enter a value: &quot;;
    cin >> amount;
    convertToHex( buf , amount );
    cout << buf << '\n';

    return 0;
}
dl_harmon@yahoo.com
 
Try this...

#include <iostream.h>

int main(int argc, char* argv[])
{
int nDecNumber;
cout << &quot;Please enter a value: &quot;;
cin >> nDecNumber;
cout << &quot;Hex value of &quot; << nDecNumber << &quot; is: &quot;;
cout.setf( ios::hex );
cout << nDecNumber << endl;

return 0;
}

Cheers,
BatVanko ;-)
 
One more approach

int val = 0xDEADBEEF;

char buffer[16];
sprintf(buffer,&quot;%x&quot;,val)
cout<<buffer;


Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top