Problem 2: (Hex to binary) Write a program that converts a nonnegative hexadecim
ID: 3831754 • Letter: P
Question
Problem 2: (Hex to binary) Write a program that converts a nonnegative hexadecimal number into a binary number. The input and output should be exactly: Enter a hexadecimal number: [USER ENTERS A NONNEGATIVE HEXADECIMAL INTEGER] Your number in binary is obXXXX. For example, an input of Oxffa should produce the output Your number in binary is ob111111111010. An input of 0x1C should produce the output Your number in binary is 0b11100. Assume the input starts with 0x or 0X. Your program must work with both capital and lower case inputs. You may not use any libraries aside from iostream and string. You may not use the dec, hex, or oct format flags provided by the iostream library. You may not use the stoi, stol, stoul, stoll, stoull, stof, stod, and stold functions provided by the string library. Hint. You may find s. erase and s. length useful, where s is of type stringExplanation / Answer
#include <iostream>
#include <string>
using namespace std;
string HexCharToNibble( char c ) {
switch (c) {
case '0': return "0000";
case '1': return "0001";
case '2': return "0010";
case '3': return "0011";
case '4': return "0100";
case '5': return "0101";
case '6': return "0110";
case '7': return "0111";
case '8': return "1000";
case '9': return "1001";
case 'A': return "1010";
case 'a': return "1010";
case 'B': return "1011";
case 'b': return "1011";
case 'C': return "1100";
case 'c': return "1100";
case 'D': return "1101";
case 'd': return "1101";
case 'E': return "1110";
case 'e': return "1110";
case 'F': return "1111";
case 'f': return "1111";
default: return "";
}
}
int main()
{
cout << "Enter a hexadecimal number: " << endl;
string hex;
cin >> hex;
string binary = "";
hex = hex.substr(2);
for(int i = 0; i < hex.length(); i++)
{
binary += HexCharToNibble(hex[i]);
}
binary.erase(0, min(binary.find_first_not_of('0'), binary.size()-1));
cout << "Your number in binary is 0b" << binary << "." << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.