mirror of
https://git.ari.lt/ari.lt/ari.lt.git
synced 2025-02-05 01:59:25 +01:00
117 lines
2.2 KiB
HTML
117 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 -> 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 && *int_string >= '0' && *int_string <= '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 >= '0' && *int_string <= '9'))
|
||
|
assert(0 && "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 -->
|