Problem with hex converter

So i made a decimal to hex converter and its almost working or at least for the first char. Any idea why it won't work?

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()
{
    int number,counter;
    string hex;
    char holder;
    cout << "Enter decimal: ";cin>>number;
    counter=number;
    while (counter!=0){
        if (number%16>=10&&number%16<=15){
            number%=16;
            holder=number%10+'A';
        }
        else {
            number%=16;
            holder=number%16+'0';
        }
        hex=holder+hex;
        counter/=16;
        number/=16;
    }
    cout << hex;
    return 0;
}

What is the purpose of line 12 and 16?
They convert the number to base 16. I tried putting them outside the if else but it still returns the same result. I also tried removing them and true it solves the problem with the second char its sometimes inaccurate for example if i enter 26 it outputs 1G, while according to a working calculator in my PC its real value is 1A. I'll try and rewrite it from scratch later
Last edited on
You don't need counter. And when you print A to F you need to subtract 10 from the current digit value (not do a % 10).

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>
#include <string>
using namespace std;

int main()
{
    int number;
    string hex;
    char digit;

    cout << "Enter decimal: ";
    cin >> number;
    if (number == 0) hex = "0";

    while (number > 0) {
        if (number % 16 >= 10)
            digit = number % 16 - 10 + 'A';
        else
            digit = number % 16 + '0';
        hex = digit + hex;
        number /= 16;
    }

    cout << hex << '\n';
}

Tett wrote:
They convert the number to base 16. I tried putting them outside the if else but it still returns the same result.

By doing that you get rid of the information about all the other hex digits.

I also tried removing them

I believe that is the right thing to do.

the second char its sometimes inaccurate for example if i enter 26 it outputs 1G, while according to a working calculator in my PC its real value is 1A.

tpb has the solution to this problem (his second sentence).
Topic archived. No new replies allowed.