D: Convert/parse uint integer to string. (@nogc)

Siarhei Siamashka siarhei.siamashka at gmail.com
Thu Nov 30 23:16:27 UTC 2023


On Friday, 24 November 2023 at 09:35:00 UTC, BoQsc wrote:
> I tried to look into https://dlang.org/phobos/std_conv.html
>
> Most of the functions inside `std.conv` seem to be dependant on 
> [Garbage Collection](https://dlang.org/spec/garbage.html).
>
> And I couldn't find a straightforward way to produce a `string` 
> value out of `uint` value.
>
> How to convert or parse `uint` value to a `string` in `@nogc` 
> way?

There are various tricks to do such conversion very fast. For 
example, the following article is essential for implementing it: 
https://lemire.me/blog/2021/06/03/computing-the-number-of-digits-of-an-integer-even-faster/

Rather than doing conversion one digit at a time, it's much more 
efficient to process multiple digits per loop iteration. Consider 
an illustrative pseudocode like this:

```D
     while (x >= 100) {
       write(twodigits_lookup_table[x % 100]); // we can handle 
two digits at once
       x /= 100;
     }
```

I have a @nogc compatible DUB module, which implements fast 
formatted output to stdout: https://github.com/ssvb/speedy-stdio 
(cutting some corners allows to squeeze some extra performance 
out of it).

The same code can be adapted to do formatted output to a memory 
buffer as well.


More information about the Digitalmars-d-learn mailing list