Created
September 5, 2021 03:34
-
-
Save mchandschuh/0f9563241f935dfd5d6e6970804fb7e0 to your computer and use it in GitHub Desktop.
Converts an integer to string in any base
This file contains hidden or 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 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think it should be
var trimmed = new ReadOnlySpan<char>(buffer, i, 32 - i);
?