# Hexadecimal string to integer value

• (2 Pages)
• 1
• 2

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

### #1 Skydiver

• Code herder

Reputation: 4265
• Posts: 13,657
• Joined: 05-May 12

# Hexadecimal string to integer value

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

```

Is This A Good Question/Topic? 4

## Replies To: Hexadecimal string to integer value

### #2 jimblumberg

Reputation: 4653
• Posts: 14,585
• 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

### #3 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 11393
• Posts: 42,930
• 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?

### #4 goodsir

Reputation: 3
• 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

### #5 GWatt

Reputation: 292
• Posts: 3,092
• 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.

### #6 Skydiver

• Code herder

Reputation: 4265
• Posts: 13,657
• Joined: 05-May 12

## Re: Hexadecimal string to integer value

Posted 26 July 2012 - 11:13 PM

GWatt, 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.

goodsir, 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.

### #7 jimblumberg

Reputation: 4653
• Posts: 14,585
• 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.

Jim

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

### #8 Skydiver

• Code herder

Reputation: 4265
• Posts: 13,657
• 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.

### #9 seijurojushi

Reputation: 1
• 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

### #10 baavgai

• Dreaming Coder

Reputation: 6339
• Posts: 13,539
• 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

### #11 goodsir

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

## Re: Hexadecimal string to integer value

Posted 27 July 2012 - 07:42 AM

seijurojushi, 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.

### #12 seijurojushi

Reputation: 1
• 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

### #13 GWatt

Reputation: 292
• Posts: 3,092
• 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

### #14 Skydiver

• Code herder

Reputation: 4265
• Posts: 13,657
• Joined: 05-May 12

## Re: Hexadecimal string to integer value

Posted 27 July 2012 - 10:29 AM

baavgai, 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.

### #15 Skydiver

• Code herder

Reputation: 4265
• Posts: 13,657
• Joined: 05-May 12

## Re: Hexadecimal string to integer value

Posted 27 July 2012 - 10:36 AM

GWatt, 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.

seijurojushi, 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

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!