Results 1 to 1 of 1

Thread: Convert to base n functions.

  1. #1

    Thread Starter
    Fanatic Member BlindSniper's Avatar
    Join Date
    Jan 2011
    Location
    South Africa
    Posts
    865

    Convert to base n functions.

    Hi all,
    It's been a while since I last posted anything in the code bank, but today I made to useful functions that I thought I would share with you guys.
    The functions convert base 10 integers to any base you like, with any alphabet you like. The second function can also convert base n numbers of any alphabet back to a base 10 integer. In the second function it would probably be more efficient to use some type of dictionary or lookup instead of index of.

    vb.net Code:
    1. Function ConvertToBase(ByVal Base As Integer, ByVal alphabet As String, ByVal number As Integer) As String
    2.         Dim modv As Integer = number
    3.         Dim div As Integer = number
    4.         Dim st As New System.Text.StringBuilder()
    5.         While div <> 0
    6.             modv = div Mod Base
    7.             div = div \ Base
    8.             st.Append(alphabet(modv))
    9.         End While
    10.         Dim rev As Char() = st.ToString.ToCharArray
    11.         Array.Reverse(rev)
    12.         Return rev
    13.     End Function
    14.  
    15.     Function ConvertFromBase(ByVal Base As Integer, ByVal alphabet As String, ByVal number As String) As Integer
    16.         Dim acc As Integer
    17.         Dim rev As Char() = number
    18.         Array.Reverse(rev)
    19.         For i = 0 To number.Length - 1
    20.             acc += (alphabet.IndexOf(rev(i))) * (Base ^ i)
    21.         Next
    22.         Return acc
    23.     End Function

    And here is an example usage

    vb.net Code:
    1. RichTextBox1.AppendText(ConvertToBase(16, "0123456789ABCDEF", 34623) & vbNewLine)
    2.         RichTextBox1.AppendText(CStr(ConvertFromBase(16, "0123456789ABCDEF", "873F")))
    Output:
    Code:
    873F
    34623
    You could probably create a third function that can convert base n for any arbitrary alphabet to another base n with an arbitrary alphabet. I can think of many interesting things these functions could be used for.
    Last edited by BlindSniper; Mar 20th, 2013 at 08:54 AM.

    Useful CodeBank Entries of mine
    Expand Function
    Code Compiler
    Sudoku Solver
    HotKeyHandler Class

    Read this to get Effective help on VBForums
    Hitchhiker's Guide to Getting Help at VBF

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width