Hexadecimal string to integer value

  • (2 Pages)
  • +
  • 1
  • 2

28 Replies - 23387 Views - Last Post: 02 October 2013 - 08:31 PM

#1 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3163
  • View blog
  • Posts: 9,556
  • Joined: 05-May 12

Hexadecimal string to integer value

Post icon  Posted 26 July 2012 - 02:21 PM

This is a simple C++ challenge to let relative new C/C++ programmers exercise their new found skills.

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;
}



Is This A Good Question/Topic? 4
  • +

Replies To: Hexadecimal string to integer value

#2 jimblumberg  Icon User is offline

  • member icon


Reputation: 3845
  • View blog
  • Posts: 11,735
  • Joined: 25-December 09

Re: Hexadecimal string to integer value

Posted 26 July 2012 - 02:29 PM

If you experts and above can't wait, how about opening/replying to a topic in the Experts/Mentors forum.

Jim
Was This Post Helpful? 0
  • +
  • -

#3 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10180
  • View blog
  • Posts: 37,594
  • Joined: 27-December 08

Re: Hexadecimal string to integer value

Posted 26 July 2012 - 08:10 PM

Or perhaps have everyone post their replies using spoiler tags? :)
Was This Post Helpful? 0
  • +
  • -

#4 goodsir  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 21
  • Joined: 25-July 12

Re: Hexadecimal string to integer value

Posted 26 July 2012 - 10:12 PM

I guess it's considered cheating because I had to wikipedia how exactly to convert hex into an integer, but it was fun anyway... Also, I'm unsure whether the subtraction scheme I use works with everything, but it worked on my computer. Haven't taken a crack at the extracredit yet.

Spoiler

Was This Post Helpful? 0
  • +
  • -

#5 GWatt  Icon User is offline

  • member icon

Reputation: 262
  • View blog
  • Posts: 3,054
  • Joined: 01-December 05

Re: Hexadecimal string to integer value

Posted 26 July 2012 - 10:56 PM

I think it makes more sense for bin2hex to return a boolean and take a int *. This way you don't run into the edge case of 0xffffffff. It's a perfectly valid number that doesn't overflow but will look like it does.
Was This Post Helpful? 0
  • +
  • -

#6 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3163
  • View blog
  • Posts: 9,556
  • Joined: 05-May 12

Re: Hexadecimal string to integer value

Posted 26 July 2012 - 11:13 PM

View PostGWatt, on 26 July 2012 - 10:56 PM, said:

I think it makes more sense for bin2hex to return a boolean and take a int *. This way you don't run into the edge case of 0xffffffff. It's a perfectly valid number that doesn't overflow but will look like it does.


Yup, I agree as well. But I figured I'd phrase the challenge in the way most C/C++ students first encounter atoi() and figuring out how to implement it. This way, it's not too far out of their comfort zone. But yes, we get more experience, we figure out that return values that look like valid return value is not really a good thing.

View Postgoodsir, on 26 July 2012 - 10:12 PM, said:

I guess it's considered cheating because I had to wikipedia how exactly to convert hex into an integer, but it was fun anyway... Also, I'm unsure whether the subtraction scheme I use works with everything, but it worked on my computer. Haven't taken a crack at the extracredit yet.

Spoiler


Don't be too down on yourself. Consider that you knew how to do your own research, learned a method, and figured out how to write code to implement that method. Some folks can't even get that first step done.
Was This Post Helpful? 0
  • +
  • -

#7 jimblumberg  Icon User is offline

  • member icon


Reputation: 3845
  • View blog
  • Posts: 11,735
  • Joined: 25-December 09

Re: Hexadecimal string to integer value

Posted 27 July 2012 - 12:42 AM

Quote

I guess it's considered cheating because I had to wikipedia how exactly to convert hex into an integer, but it was fun anyway...

In my opinion that's not cheating at all. Part of becoming a good programmer is researching methods and algorithms to accomplish your requirements.

Edit: That is as long as you took time to understand how and why the algorithm functions.

Glad you had some fun.

Jim

This post has been edited by jimblumberg: 27 July 2012 - 01:06 AM

Was This Post Helpful? 1
  • +
  • -

#8 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3163
  • View blog
  • Posts: 9,556
  • Joined: 05-May 12

Re: Hexadecimal string to integer value

Posted 27 July 2012 - 12:54 AM

Kudos should go to Jim, by the way, for encouraging me to post this challenge. I hope that it proves interesting and fun for everybody.

Even if you've implemented this code before, it maybe fun to try it again or try a different approach. For full disclosure, I implemented two solutions to the problem taking completely different approaches. In one approach, I completely biffed the "edge" case in the extra credit part and I had to stare at my code for about 3 minutes going "Whiskey Tango Foxtrot?" until I found the off-by-one error.
Was This Post Helpful? 0
  • +
  • -

#9 seijurojushi  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 35
  • Joined: 24-July 12

Re: Hexadecimal string to integer value

Posted 27 July 2012 - 04:31 AM

Here's what I got for the conversion bit:
Spoiler


Not sure if I was allowed to add string and define nullptr, but could not get it to work otherwise :)

Thank you for the lesson ^^
Was This Post Helpful? 0
  • +
  • -

#10 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5642
  • View blog
  • Posts: 12,359
  • Joined: 16-October 07

Re: Hexadecimal string to integer value

Posted 27 July 2012 - 05:53 AM

Fun!

Right first version:
Spoiler


This works well enough, but the extra credit test makes wonky assumptions. Like I'd want a partial parse of a string.

To allow for the test, we make a minor change.
Spoiler


There is a hold out. However, I believe it makes an invalid assumption as to the correct result. So, I fixed the test:
int check[] = {0, 0xC0FFEE, 0x0110, 0xed, 0, 0, 0x800000000, -1};



It think that's more fair than imposing logic contrary to the compiler.

Also, because parallel arrays are evil... I compulsively fixed the rest of the test
Spoiler

Was This Post Helpful? 2
  • +
  • -

#11 goodsir  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 21
  • Joined: 25-July 12

Re: Hexadecimal string to integer value

Posted 27 July 2012 - 07:42 AM

View Postseijurojushi, on 27 July 2012 - 04:31 AM, said:

Here's what I got for the conversion bit:
Spoiler


Not sure if I was allowed to add string and define nullptr, but could not get it to work otherwise :)

Thank you for the lesson ^^

Yeah, I had a problem with nullptr too. It turns out to be a constant introduced in c++ 11.

Quote

C++11 corrects this by introducing a new keyword to serve as a distinguished null pointer constant: nullptr. It is of type nullptr_t, which is implicitly convertible and comparable to any pointer type or pointer-to-member type. It is not implicitly convertible or comparable to integral types, except for bool. While the original proposal specified that an rvalue of type nullptr should not be convertible to bool, the core language working group decided that such a conversion would be desirable, for consistency with regular pointer types. The proposed wording changes were unanimously voted into the Working Paper in June 2008.[2]
For backwards compatibility reasons, 0 remains a valid null pointer constant.

Was This Post Helpful? 1
  • +
  • -

#12 seijurojushi  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 35
  • Joined: 24-July 12

Re: Hexadecimal string to integer value

Posted 27 July 2012 - 08:04 AM

hehe I did hex>bin>decimal...
the sigbature said hex to bin so i started writing that... oh well now i have both :P
Was This Post Helpful? 1
  • +
  • -

#13 GWatt  Icon User is offline

  • member icon

Reputation: 262
  • View blog
  • Posts: 3,054
  • Joined: 01-December 05

Re: Hexadecimal string to integer value

Posted 27 July 2012 - 08:27 AM

I did something very similar to baavgai in that I made an actual test case record but with an additional field for valid conversion. I changed the challenge slightly and pass a int * instead of behaving like atoi.
Spoiler

Was This Post Helpful? 1
  • +
  • -

#14 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3163
  • View blog
  • Posts: 9,556
  • Joined: 05-May 12

Re: Hexadecimal string to integer value

Posted 27 July 2012 - 10:29 AM

View Postbaavgai, on 27 July 2012 - 05:53 AM, said:

Fun!

Right first version:
Spoiler


This works well enough, but the extra credit test makes wonky assumptions. Like I'd want a partial parse of a string.

To allow for the test, we make a minor change.
Spoiler


There is a hold out. However, I believe it makes an invalid assumption as to the correct result. So, I fixed the test:
int check[] = {0, 0xC0FFEE, 0x0110, 0xed, 0, 0, 0x800000000, -1};



It think that's more fair than imposing logic contrary to the compiler.

Also, because parallel arrays are evil... I compulsively fixed the rest of the test
Spoiler


The partial parse of a string matches the behavior of atoi() which this hex2bin() is trying to parallel.

Nice job swapping to a test record rather than the array. That would have been my preference as well. I was trying to keep things simple so that a newbie who hasn't encountered struct's yet wouldn't be sidetracked by something new. Unfortunately, I shot myself in the foot by introducing nullptr. *sigh*

I'm curious which compiler you are using that has 64-bit integers as its default.
Was This Post Helpful? 0
  • +
  • -

#15 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3163
  • View blog
  • Posts: 9,556
  • Joined: 05-May 12

Re: Hexadecimal string to integer value

Posted 27 July 2012 - 10:36 AM

View PostGWatt, on 27 July 2012 - 08:27 AM, said:

I did something very similar to baavgai in that I made an actual test case record but with an additional field for valid conversion. I changed the challenge slightly and pass a int * instead of behaving like atoi.
Spoiler


Nice job also adding the null pointer to a string as a test case! I was very tempted to add that as a test case. Modern production code should handle such a case, but most of what is taught at schools and in books seems to skip the parameter checks.

View Postseijurojushi, on 27 July 2012 - 08:04 AM, said:

hehe I did hex>bin>decimal...
the sigbature said hex to bin so i started writing that... oh well now i have both :P


Maybe the long way around, but you learned new things along the way as well. Sounds like you had fun doing this challenge as well!
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2