Braden Smith
Braden Smith

Reputation: 11

Converting binary to hex: error only on 2-7

I'm converting 4digit binary to single digit hex using a basic switch-case statement and the code will not run for digits 0010-0111 for some reason and I have no idea why.

Here is what I have:

void BinHex() {
        int binin;
        cout << "Enter Binary(####): " << endl;
        cin >> binin;

        switch(binin){
                case 0000: cout << "Hex: 0" << endl; break;
                case 0001: cout << "Hex: 1" << endl; break;
                case 0010: cout << "Hex: 2" << endl; break;
                ...
        }
}

All numbers 0,1,8-15 work perfectly fine but the middle numbers do not. Any ideas on what could be causing this to error out/not run?

Upvotes: 1

Views: 70

Answers (1)

Barry
Barry

Reputation: 303007

This case:

case 0010: cout<<"Hex: 2\n"; break;

Will not fire for binin == 10. It will fire for binin == 8, because 0010 is an octal literal. Just drop the leading 0s so that the value gets interpreted as a decimal literal instead.

Upvotes: 5

Related Questions