Skip to content

Instantly share code, notes, and snippets.

@skarllot
Created February 25, 2024 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skarllot/c663bdc4114080a8e6fae28dd80f7747 to your computer and use it in GitHub Desktop.
Save skarllot/c663bdc4114080a8e6fae28dd80f7747 to your computer and use it in GitHub Desktop.
Allocation free int to string (incomplete)
public static class FormatExtensions
{
public static string Int32ToString(int a)
{
const int radix = 10;
const int maxLength = 11;
Span<char> str = stackalloc char[maxLength];
int i = str.Length;
bool isNegative = a < 0;
if (a <= 0) // handles 0 and int.MinValue special cases
{
a = -Math.DivRem(a, radix, out int remainder);
str[--i] = (char)(-remainder + '0');
}
while (a != 0)
{
a = Math.DivRem(a, radix, out int remainder);
str[--i] = (char)(remainder + '0');
}
if (isNegative)
{
str[--i] = '-';
}
return str.Slice(i, str.Length - i).ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment