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

Mark Davies markd at trap10.net
Tue Nov 28 08:51:21 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 did it this way ...

```
import std.stdio;

char[10] longToString(long n) @nogc
{
	char[10] x;
	ulong power;
	
	x[0] = '-'*(n<0);

	long t = (n<0)*-n + (n>0)*n ;

	while (n != 0)
	{
		power++;
		n /= 10;
	}
	
	power -= (x[0] != '-');
	
	while (t > 0)
	{
		x[power] = (t % 10) + '0';
		power--;
		t /= 10;
	}
	
	return x;
}


int main()
{
	long p = 12345;
	char[10] r = longToString(p);
	writeln(r);
	
	p = -12345;
	r = longToString(p);
	writeln(r);
	
	return 0;
}
```


More information about the Digitalmars-d-learn mailing list