If you're doing this to learn how to do it, ignore this post. If you're using this function because you need to convert a string of hex numbers to an int
, you should take a walk in your standard library. The standard function strtol()
converts a string to a long
, which can be cast down to an int
(or an unsigned int
while were at it). The third argument is the base to convert to - in this case, you would want base 16 for hexadecimal. Also, if given base 0, it will assume hex if the string begins with 0x
, octal if it begins with 0
, and decimal otherwise. It's a very useful function.
EDIT: Just noticed this, but while we're here, it's worth mentioning that you should generally not use an int
to index arrays. The C standard defines a type, called size_t
, which is designed to store array indices. It is generally an unsigned int
or unsigned long
or something, but is guaranteed to be big enough to store any array or pointer offset you can use.
The problem with using just an int
is that, theoretically, maybe, someday, someone could pass a string longer than INT_MAX
, and then your int
will overflow, probably wrap around, and start reading memory it probably shouldn't because it's using a negative index. This is highly unlikely, especially for a function like this, because the int
value you return will overflow long before your int
counter overflows, but it is an important thing to keep in mind.
To be technically correct, you should only use size_t
type variables to index arrays, or at least only use unsigned
types, unless you really want to try to access negative elements (which is usually a bad idea unless you know what you're doing). However, it's not a huge issue here.