Vinod
Vinod

Reputation: 1091

convert a string to unsigned long int of a given base: generic algorithm

As part of compiling proprietary driver code, I am forced remove inclusion of <stdlib.h> to address type conflicts arising with kernel include files. The last mile in getting the code compiled and linked successfully seems to be to replace the C standard library function strtoul() with a hand coded method, so that the dependency on <stdlib.h> can be completely removed. But the catch is that the hand written code should address all the bases between 0 and 16 (inclusive) for conversion.

Can anyone suggest a generic algorithm to meet this requirement?

TIA

Vinod

Upvotes: 0

Views: 114

Answers (1)

dbush
dbush

Reputation: 224352

Take the string and base as parameters. Start with a sum of 0. Then for each character in the string going left to right:

  • If it's a digit, convert to a value between 0 and 9
  • If it's a letter (A-F or a-f), convert to a value between 10 and 16
  • Multiply the current sum by the base, then add the value to the sum.

Upvotes: 2

Related Questions