The problem is to implement the classic hex2bin() function. It takes a string of hexadecimal digits as input and returns an integer as the output. For example, the input string "1F" should return 31. It should try to interpret as many hexadecimal digits as it can.
Below is a small test harness. All you need to do is modify the body of hex2bin(). Remember to post your solutions for the body of hex2bin() with [spoiler] tags to keep the challenge fresh for everybody.
For extra credit, uncomment the call to ExtraCreditTest() to try your hand at handling larger values and invalid input. It assumes a 32-bit integer as the native int type. If an integer overflows, your implementation should return -1.
(We ask that C/C++ experts refrain from responding with their solutions until most of the newbies get a chance to post.)
#include <iostream>
int hex2bin(const char *hexString);
void TestIt(char * inputs[], const int check[] )
{
for(int i = 0; inputs[i] != nullptr; i++)
{
int value = hex2bin(inputs[i]);
std::cout << "Hex string: " << inputs[i]
<< " is " << value << " in decimal. "
<< ( value == check[i] ? "Correct" : "Incorrect" )
<< std::endl;
}
}
void BasicTest()
{
char * inputs[] = { "0", "C", "9A", "71", "FFFF", "bad", "CAFE", "f00d", nullptr };
int check[] = { 0, 0xC, 0x9A, 0x71, 0xFFFF, 0xbad, 0xCAFE, 0xf00d, -1 };
std::cout << "Basic tests: " << std::endl;
TestIt(inputs, check);
}
void ExtraCreditTest()
{
char * inputs[] = { "", "C0FFEE", "0110 65", "edge", "0x12", "$29", "800000000" nullptr };
int check[] = { 0, 0xC0FFEE, 0x0110, 0xed, 0, 0, -1, -1 };
std::cout << "Extra credit tests: " << std::endl;
TestIt(inputs, check);
}
int main()
{
BasicTest();
// Uncomment the line below for an extra challenge.
// ExtraCreditTest();
return 0;
}
int hex2bin(const char *hexString)
{
int value = 0;
// Write your implementation here.
return value;
}

New Topic/Question
Reply


MultiQuote









|