Fast atoi in C(++)

2022-01-20 16:58:31 EET | back | home | git


std::atoi (in C++) is fast on its own but can be slow so for stuff you need speed you can use this:

``` int fast_atoi(const char *int_string) { int value = 0;

while (*int_string && *int_string >= '0' && *int_string <= '9')
    value = value * 10 + (*int_string++ - '0');

return value;

} ```

This requires no headers, just pure C (also valid in C++), you can put this into your code and it will just work!

```

include

int fast_atoi(char *int_string) { int value = 0;

while (*int_string) {
    if (!(*int_string >= '0' && *int_string <= '9'))
        assert(0 && "atoi(): invalid int_string");

    value = value * 10 + (*int_string++ - '0');
}

return value;

} ```

This option is throws an assertion error if it encounters an invalid string but this requires assert.h as a dependency.

In C++ assert.h should be replaced with cassert .