Skip to content

Instantly share code, notes, and snippets.

@mchandschuh
Created September 5, 2021 03:34
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 mchandschuh/0f9563241f935dfd5d6e6970804fb7e0 to your computer and use it in GitHub Desktop.
Save mchandschuh/0f9563241f935dfd5d6e6970804fb7e0 to your computer and use it in GitHub Desktop.
Converts an integer to string in any base
public static string IntToStringFast(int value, char[] baseChars)
{
// 32 is the worst cast buffer size for base 2 and int.MaxValue
var i = 32;
var buffer = new char[i];
var targetBase = baseChars.Length;
do
{
buffer[--i] = baseChars[value % targetBase];
value /= targetBase;
}
while (value > 0);
// avoid re-allocating another array just to trim the size
// by using string's ReadOnlySpan<char> ctor
var trimmed = new ReadOnlySpan<char>(buffer, 0, 32 - i);
return new string(trimmed);
}
@moon6969
Copy link

moon6969 commented Apr 9, 2022

I think it should be var trimmed = new ReadOnlySpan<char>(buffer, i, 32 - i);?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment