Christopher Clarke Christopher Clarke - 1 year ago 91
C Question

Floating point equivalent to strtol() in C

converts the inputed string str to a long value of any specified base of 2 to 36.
offers a similar functionality but without allowing your to specify base. Is there another function that does the same as
but allows you to select base?

e.g Lets say 101.101 is inputted as a string. I want to be able to do

strtof("101.101", null, 2);

and get an output of

Answer Source

You can parse the string to split it in the . and convert the part before and the part after to decimal. Afterwards, you can create a float out of that string. Here is a simple function that accomplishes that.

float new_strtof(char* const ostr, char** endptr, unsigned char base)
    char* str = (char*)malloc(strlen(ostr) + 1);
    strcpy(str, ostr);
    const char* dot = ".";

    /* I do not validate any input here, nor do I do anything with endptr */      //Let's assume input of 101.1101, null, 2 (binary)
    char *cbefore_the_dot = strtok(str, dot); //Will be 101
    char *cafter_the_dot = strtok(NULL, dot); //Will be 0101

    float f = (float)strtol (cbefore_the_dot, 0, base); //Base would be 2 = binary. This would be 101 in decimal which is 5
    int i;
    char n[2] = { 0 }; //will be just for a digit at a time

    for(i = 0 ; cafter_the_dot[i] ; i++) //iterating the fraction string
        n[0] = cafter_the_dot[i];
        f += strtol(n, 0, base) * pow(base, -(i + 1)); //converting the fraction part

    return f;

One could manage this in a more efficient and less dirty way but this is just an example to show you the idea behind this. The above works well for me.

Don't forget to #include <math.h> and compile with -lm flag. An example would be gcc file.c -o file -lm.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download