Quickest way to convert a base 10 number to any base in .NET?

后端 未结 12 1250
予麋鹿
予麋鹿 2020-11-22 04:07

I have and old(ish) C# method I wrote that takes a number and converts it to any base:

string ConvertToBase(int number, char[] baseChars);

12条回答
  •  悲&欢浪女
    2020-11-22 04:39

    If anyone is seeking a VB option, this was based on Pavel's answer:

    Public Shared Function ToBase(base10 As Long, Optional baseChars As String = "0123456789ABCDEFGHIJKLMNOPQRTSUVWXYZ") As String
    
        If baseChars.Length < 2 Then Throw New ArgumentException("baseChars must be at least 2 chars long")
    
        If base10 = 0 Then Return baseChars(0)
    
        Dim isNegative = base10 < 0
        Dim radix = baseChars.Length
        Dim index As Integer = 64 'because it's how long a string will be if the basechars are 2 long (binary)
        Dim chars(index) As Char '65 chars, 64 from above plus one for sign if it's negative
    
        base10 = Math.Abs(base10)
    
    
        While base10 > 0
            chars(index) = baseChars(base10 Mod radix)
            base10 \= radix
    
            index -= 1
        End While
    
        If isNegative Then
            chars(index) = "-"c
            index -= 1
        End If
    
        Return New String(chars, index + 1, UBound(chars) - index)
    
    End Function
    

提交回复
热议问题