Convert a Decimal Number in a Given Base

By | 2019-08-23

Just a little something to help you do math in different numbering systems.

Option Explicit

'Convert a decimal number in another base
Public Function CBase(ByVal number As Long, ByVal base As Long) As String
   'symbols to code the number
   Const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   Dim r As Long

   'verify if there are enought symbols to code the number in the selected base
   If base < 2 Or base > Len(chars) Then Exit Function
   CBase = ""
   Do While number >= base
      r = number Mod base
      CBase = Mid(chars, r + 1, 1) & CBase
      number = number \ base
   Loop
   CBase = Mid(chars, number + 1, 1) & CBase
End Function

Usage

'Create a form with a button and two text box,
'in the first text box enter the decimal number to convert
'in the second enter the new base in which the number will be converted
Private Sub Command1_Click()
   MsgBox CBase(Val(Text1.Text), Val(Text2.Text))
End Sub

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.