When dealing with different progressive values, advance transformation is often required. Although the built -in method supports limited transformations, the .NET lacks a general -purpose transformation mechanism.
Custom conversion function Convert.ToString
In order to realize the transformation of any advancement, it can realize its own practical function. A simple method is toely divide the numbers in the goal and accumulate the remaining numbers in the opposite order:
Performance optimization
public static string IntToString(int value, char[] baseChars) { string result = string.Empty; int targetBase = baseChars.Length; do { result = baseChars[value % targetBase] + result; value = value / targetBase; } while (value > 0); return result; }
This method is much faster for large numbers (especially those who have produced longer representations in the target base). However, for one digit, the original method may be faster.
<自> Use custom foundation character
public static string IntToStringFast(int value, char[] baseChars) { // 基数为2且值为int.MaxValue时的最坏情况缓冲区大小 int i = 32; char[] buffer = new char[i]; int targetBase = baseChars.Length; do { buffer[--i] = baseChars[value % targetBase]; value = value / targetBase; } while (value > 0); return new string(buffer, i, 32 - i); }
and IntToString
Allow you to specify any array of any base character. This can use custom bases, such as hexadic (base 26, use of uppercase and lowercase letters) or sixty -in -proof (base 60).
The above is the detailed content of How Can I Efficiently Perform Base Conversions in .NET?. For more information, please follow other related articles on the PHP Chinese website!