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

Ferhat Kurtulmuş aferust at gmail.com
Fri Nov 24 13:05:30 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?

I guess there are third-party libraries doing this. One would use 
stdc functions such as sprintf. Probably, there should be a more 
d-ish way.
```
import core.stdc.stdio : sprintf;
import core.stdc.math : log10;

import std.exception : assumeUnique;
import std.stdio : writeln;

     size_t nod(int num){
       return cast(size_t)((num==0)?1:log10(num)+1);
     }

     void main()
     {
        int myint = 23;

        char[80] str;

        sprintf(str.ptr, "%d", myint);

        string _dstring = str[0..nod(myint)].assumeUnique;

        writeln(_dstring);

}
```


More information about the Digitalmars-d-learn mailing list