Question: HEX to BINARY HELP! I need this code to work properly. When I input 0x1C, I should get 0b11100. Rather I get a wrong answer:
HEX to BINARY HELP! I need this code to work properly. When I input 0x1C, I should get 0b11100. Rather I get a wrong answer: 0b00011100. When I do 0x0 i should get 0b0, which works fine. Please provide a correct solution. THANKS!
#include #include using namespace std;
int main() { string hex, dec; // string containing hexadecimal and binary numbers bool invalid_number = false; // if number is invalid hexadecimal number // input of hexadecimal number cout << "Enter a hexadecimal number: "; getline(cin, hex); dec = ""; // assign dec to empty string // since the first 2 character of hexadecimal starts from 0x, ignore them during conversion for (size_t i = 2; i { if (invalid_number) // if any character is invalid exit from loop break; // switch command to convert the hexadecimal character to binary strings switch (hex.at(i)) { case '0': dec = dec + "0000"; break; case '1': dec = dec + "0001"; break; case '2': dec = dec + "0010"; break; case '3': dec = dec + "0011"; break; case '4': dec = dec + "0100"; break; case '5': dec = dec + "0101"; break; case '6': dec = dec + "0110"; break; case '7': dec = dec + "0111"; break; case '8': dec = dec + "1000"; break; case '9': dec = dec + "1001"; break; case 'a': case 'A': dec = dec + "1010"; break; case 'b': case 'B': dec = dec + "1011"; break; case 'c': case 'C': dec = dec + "1100"; break; case 'd': case 'D': dec = dec + "1101"; break; case 'e': case 'E': dec = dec + "1110"; break; case 'f': case 'F': dec = dec + "1111"; break; default: cout << " Invalid hexadecimal number"; invalid_number = true; break; } } // if number is not invalid then remove the leading zeros from binary numbar and add 0b at the start if (!invalid_number) { if (dec == "0000") { dec = "0"; } dec = "0b" + dec; cout << "Your number in binary is " << dec; cout << "." << endl; } return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
