Skip to content

Instantly share code, notes, and snippets.

@mchandschuh
Created September 5, 2021 03:34
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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