Decimal to Hexadecimal Question



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

using namespace std;
int main()
{
    long dec,rem,i=1,sum=0;
    cout<<"Enter the decimal to be converted:";
    cin>>dec;
    if(dec<=0){
        cout << "Invalid Number!\tEnter a positive number Please\n";
        exit(0);
    }
    do
    {
        rem=dec%2;
        sum=sum + (i*rem);
        dec=dec/2;
        i=i*10;
    }while(dec>0);
    cout<<"The binary of the given number is:"<<sum<<endl;
    cin.get();
    cin.get();
 
    return 0;
}


How can I modify this to find Decimal to Hexadecimal bcz after 9,hexadecimal notation starts with A,B,...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>

int main()
{
    const unsigned int HEX_BASE = 16 ;
    const std::string hex_digits = "0123456789abcdef" ;

    unsigned int number ;
    std::cin >> number ;

    unsigned int n = number ;
    std::string hex_string ;

    if( n == 0 ) hex_string += '0' ;

    while( n != 0 )
    {
        hex_string = hex_digits[ n % HEX_BASE ] + hex_string ;
        n /= HEX_BASE ;
    }

    std::cout << "0x" << hex_string << ' ' << std::hex << std::showbase << number << '\n' ;
}

http://coliru.stacked-crooked.com/a/f3ef2e9fe1f2b170
Topic archived. No new replies allowed.