Friday, 20 June 2014

C++ program to convert character to different numeral systems

Here are C++ program to convert character to decimal, binary, octal and hexadecimal.


C++ program to convert character to decimal
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
    char ascii;
    cout<<"Enter the character : ";
    ascii=getche();
    cout<<"\nDecimal value of character : "<<int(ascii);
    return 0;
}

OUTPUT




C++ program to convert character to binary
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
    char ascii;
    long rem,temp=1,decimal,binary=0;
    cout<<"Enter the character ";
    ascii=getche();
    decimal=int(ascii);
    while(decimal)
    {
        rem=decimal%2;
        decimal/=2;
        binary+=rem*temp;
        temp*=10;
    }
    cout<<"\nBinary value of character : "<<binary;
    return 0;
}

OUTPUT




C++ program to convert character to octal
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
    char ascii;
    long octal=0,decimal=0,rem,num,temp=1;
    cout<<"Enter the character ";
    ascii=getche();
    decimal=int(ascii);
    while(decimal)
    {
        rem=decimal%8;
        decimal/=8;
        octal=octal+rem*temp;
        temp*=10;
    }
    cout<<"\nOctal equivalent : "<<octal;
    return 0;
}

OUTPUT




C++ program to convert character to hexadecimal
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
    char ascii;
    long decimal,hexa[20],i;
    cout<<"Enter the character ";
    ascii=getche();
    decimal=int(ascii);
    for(i=0;decimal>0;i++)
    {
        hexa[i]=decimal%16;
        decimal/=16;
    }
    cout<<"Hexadecimal equivalent : ";
    while(i>0)
    {
        i--;
        if(hexa[i]>9)
            cout<<char(55+hexa[i]);
        else
            cout<<hexa[i];
    }
    return 0;
}

OUTPUT




No comments:

Post a Comment