asim
asim

Reputation: 29

C++ program to convert decimal to hexadecimal

I wrote a program to convert a decimal string to hexadecimal by using a switch command to the letter but if I use char the program does not work well! Without switch I can't deal with the number above 9 .. I hope that u did understand me because my language is not that good.

So this my program

BTW if put it int instead of char it work fine but it's become 11 instead of B

#include <iostream>
using namespace std;
int main()
{
    int n, i, c=0, t;
    char a[50];

    cout << "Enter a decmail number :\n";
    cin >> n;
    t = n;

    for (i = 0; t > 0; i++)
    {
        if (a[i] % 16 > 9)
        {
            switch(a[i])
            {
                case 10 : a[i] = 'A'; break;
                case 11 : a[i] = 'B'; break;
                case 12 : a[i] = 'C'; break;
                case 13 : a[i] = 'D'; break;
                case 14 : a[i] = 'E'; break;
                case 15 : a[i] = 'F'; break;
            }
        }
        else
        {
            a[i] = t % 16;
        }
        t = t / 16;
    }    
    cout << n << " In hexdecmail = ";
    for(c = i - 1; c >= 0; c--)
    {
        cout << a[c];
    }
}

Upvotes: 1

Views: 3451

Answers (1)

Ajay Brahmakshatriya
Ajay Brahmakshatriya

Reputation: 9213

The problem here is that 1 is not the same as '1'. 1 is the number one while '1' is a character constant. To convert 1 to '1' you have to add '0' to the number. So you can change the line a[i] = t%16; to a[i] = t%16 + '0';

Also instead of putting the if condition and the switch case on a[i], you need to put it on t%16, because a[i] is not yet set. Rest it should work fine.

Edit : To understand how the conversation from number to character constants work you need to understand how characters are represented internally.

Each character like a-z, A-Z , 0-9 and the special characters are assigned a number between 0 and 256. This numbering is called the ASCII value of the character. You can find the list of all ASCII values here.

The ASCII value of '0' is 48. That of '1' is 49, '2' is 50 and so on. Now what you have is the number (you get by doing t%16). Say it is 3 . To convert to its ASCII code(51) you will have to add 48. Similarly all numbers between 0-9 can be converted to their ASCII values by adding 48. This is because the ASCII values of the digits are continuous.

Often it is difficult to remember the ASCII value 48. So instead you can just write '0' which internally means 48.

I hope this helps.

Upvotes: 5

Related Questions