I don't want to unnecessarily re-invent the wheel, but I have been looking for the functionality of strtod but with a base parameter (2,8,10,16). (I know strtoul allows a base parameter but I'm looking for return type double). Any advice / pointers in the right direction? Thanks.
2 Answers
For arbitrary base, this is a hard problem, but as long as your base is a power of two, the plain naive algorithm will work just fine.
strtod
(in C99) supports hex floats in the same format as the C language's hex float constants. 0x
prefix is required, p
separates the exponent, and the exponent is in base 10 and represents a power of 2. If you need to support pre-C99 libraries, you'll have no such luck. But since you need base 2/4/8 too, it's probably just best to roll your own anyway.
Edit: An outline of the naive algorithm:
- Start with a floating point accumulator variable (
double
or whatever, as you prefer) initialized to 0. - Starting from the leftmost digit, and up to the radix point, for each character you process, multiply the accumulator by the base and add the value of the character as a digit.
- After the radix point, start a new running place-value variable, initially 1/base. On each character you process, add the digit value times the place-value variable, and then divide the place-value variable by base.
- If you see the exponent character, read the number following it as an integer and use one of the standard library functions to scale a floating point number by a power of 2.
If you want to handle potentially rounding up forms that have too many digits, you have to work out that logic once you exceed the number of significant places in step 2 or 3. Otherwise you can ignore that.

- 208,859
- 35
- 376
- 711
-
Thanks. I believe I'll roll my own function for the floating point portion and pass the integer portion to strtol, then add the results together so I can stick to C89. – jparanich Feb 10 '11 at 21:29
-
Actually that doesn't work. If the value is too big to fit in `long`, it will fail. – R.. GitHub STOP HELPING ICE Feb 10 '11 at 21:41
-
See my updates regarding how to implement the "naive algorithm". – R.. GitHub STOP HELPING ICE Feb 10 '11 at 22:06
Unlikely - I have never seen floating point numbers coded as 'decimals' in other number bases.

- 94,801
- 28
- 188
- 263
-
1On the contrary, hex floats are part of the C standard. – R.. GitHub STOP HELPING ICE Feb 10 '11 at 21:07
-
It's also worth noting that in order to store exact float values efficiently, and also in order to avoid the risk of reading back the incorrect value due to bugs in other software, you really should always store floats in a power-of-two base when printing them as text. – R.. GitHub STOP HELPING ICE Feb 10 '11 at 21:40
-
@R - they are in the C99 standard but aren't in C++. Even in C they are pretty rare. – Martin Beckett Feb 10 '11 at 22:21