0

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

Vinod
  • 925
  • 8
  • 9
  • There are many cases for full `strtoul()` functionality. I recommend whatever you code, consider [code review](https://codereview.stackexchange.com/). – chux - Reinstate Monica Jun 15 '21 at 02:28
  • Vinod, `strtoul()` handles bases 2-36 (and 0). You want _all the bases between 0 and 16_. What other differences are OK? – chux - Reinstate Monica Jun 15 '21 at 03:44
  • @chux-ReinstateMonica I was originally thinking of replacing strtoul() with kstrtoul() which handles only up to base 16....but ideally I would want all the bases supported by strtoul()... – Vinod Jun 15 '21 at 03:49
  • 1
    Vinod, there is the case of `base == 0` steering to bases 8,10, or 16. `errno` setting and value capping on out of range. Leading `+,-` concerns and `unsigned long` as 32, 64, ... size. Optional `0x` on base 16 to handle. There is `char **endptr` to handle especially with odd cases like `"0x"`. The leading white-space is _locale_ sensitive. I suspect you do not want a true `strtoul()` equivalent - but a _light_ one as already answer below. – chux - Reinstate Monica Jun 15 '21 at 03:58

1 Answers1

2

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.
dbush
  • 205,898
  • 23
  • 218
  • 273