ari.lt/page/blog/blogs/Fast-atoi-in-c(++)_8279372928.html
Ari Archer e07bc9774b update @ Thu 20 Jan 16:59:33 EET 2022
Signed-off-by: Ari Archer <truncateddinosour@gmail.com>
2022-01-20 16:59:33 +02:00

116 lines
2.2 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta content="IE=edge" http-equiv="X-UA-Compatible"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title>
Ari::web -&gt; Blog
</title>
<meta content="website webdev linux programming ari terminal dark blog javascript opensource free" name="keywords"/>
<meta content="Blog on 2022-01-20 16:58:31 EET - Fast atoi in C(++)" name="description"/>
<meta content="follow" name="robots"/>
</head>
<body>
<div>
<h1>
Fast atoi in C(++)
</h1>
<p>
2022-01-20 16:58:31 EET |
<a href="..">
back
</a>
|
<a href="/">
home
</a>
|
<a href="/git">
git
</a>
</p>
<hr/>
<p>
<code>
std::atoi
</code>
(in C++) is fast on its own but can be slow
so for stuff you need speed you can use this:
</p>
<ul>
<li>
Option one
</li>
</ul>
<p>
```
int fast_atoi(const char *int_string) {
int value = 0;
</p>
<pre><code>while (*int_string &amp;&amp; *int_string &gt;= '0' &amp;&amp; *int_string &lt;= '9')
value = value * 10 + (*int_string++ - '0');
return value;
</code></pre>
<p>
}
```
</p>
<p>
This requires no headers, just pure C (also valid in C++),
you can put this into your code and it will just work!
</p>
<ul>
<li>
Option two
</li>
</ul>
<p>
```
</p>
<h1>
include
<assert.h>
</assert.h>
</h1>
<p>
int fast_atoi(char *int_string) {
int value = 0;
</p>
<pre><code>while (*int_string) {
if (!(*int_string &gt;= '0' &amp;&amp; *int_string &lt;= '9'))
assert(0 &amp;&amp; "atoi(): invalid int_string");
value = value * 10 + (*int_string++ - '0');
}
return value;
</code></pre>
<p>
}
```
</p>
<p>
This option is throws an assertion error if it encounters an
invalid string but this requires
<code>
assert.h
</code>
as a dependency.
</p>
<p>
In C++
<code>
assert.h
</code>
should be replaced with
<code>
cassert
</code>
.
</p>
</div>
</body>
</html>
<!-- this is automatically generated by scripts/add_blog -->