Skip to main content
3 of 3
deleted 658 characters in body
Arnoud Buzing
  • 9.9k
  • 2
  • 50
  • 58

updated based on comment feedback

One more approach, using LibraryLink. Create a C file called strto.cpp as follows:

#include <cstdlib> #include "WolframLibrary.h" EXTERN_C DLLEXPORT int wolfram_strtol(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) { char *string; mint base; mint result; string = MArgument_getUTF8String(Args[0]); base = MArgument_getInteger(Args[1]); result = strtol(string, NULL,base); MArgument_setInteger(Res,result); return LIBRARY_NO_ERROR; } EXTERN_C DLLEXPORT int wolfram_strtod(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) { char *string; mint base; mreal result; string = MArgument_getUTF8String(Args[0]); result = strtod(string, NULL); MArgument_setReal(Res,result); return LIBRARY_NO_ERROR; } 

This is a very thin wrapper for the C++ strtol and strtod standard library functions.

Create the library:

Needs["CCompilerDriver`"]; lib = CreateLibrary[{"wolfram_strto.cpp"}, "wolfram_strto"] 

Load the two library functions:

strtol = LibraryFunctionLoad[lib, "wolfram_strtol", {"UTF8String", Integer}, Integer]; strtod = LibraryFunctionLoad[lib, "wolfram_strtod", {"UTF8String"}, Real]; 

Test the basics:

strtol["104", 10] 

This should return the integer 104

strtod["10e4"] 

This should return the real 100000.

Check some harder cases:

strtod /@ {"3.14159", "3.14159e-02", "3.14159e+02", "1.23e-5", "1E6", "1.734E-003", "2.12e1"} 

Try a hex number:

strtol["0x2AF3", 0] 

This should return 10995 (e.g. same as 16^^2AF3)

Measure the elapsed time to 15,000 randomly generated reals:

strings = ToString @ Row[ RandomChoice /@ {{"-", ""}, {#}, {"e"}, {"-", ""}, Range@12}] & /@ RandomReal[{0, 10}, 15000] First@AbsoluteTiming[ strtod /@ strings] 

Returns in about 0.017 seconds on my machine.

For big numbers, there is another difference:

Internal`StringToDouble["1e4000"] strtod["1e4000"] 

The StringToDouble function gives $Failed["IEEE Exception"] and the strtod function gives DirectedInfinity[1].

In the case of underflow you get, respectively, $Failed["IEEE Underflow"] and 0.

Also, StringToDouble recognizes WL notation (e.g. 6.022*^23) and strtod does not recognize this format.

Arnoud Buzing
  • 9.9k
  • 2
  • 50
  • 58