Created
February 25, 2024 16:22
-
-
Save skarllot/c663bdc4114080a8e6fae28dd80f7747 to your computer and use it in GitHub Desktop.
Allocation free int to string (incomplete)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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