Simple VB.net Code for Decimal-Hexadecimal Conversion

 

 

 

 

         

Shown below is a simple VB.net code for Decimal-to-Hexadecimal and Hexadecimal-to-Decimal conversion, along with a screenshot of the form used with it, for reference by students learning to program in VB.net in the context of electronics and computer engineering. Clicking on the left button would convert the decimal value in the "Decimal" textbox into its hexadecimal equivalent inside the "Hexadecimal" textbox. On the other hand, clicking on the right button would do the opposite.

 

  

  

  

Public Class frmMain Inherits System.Windows.Forms.Form
          

Function baseN2dec(ByVal value, ByVal inBase) As String
'Converts any base to base 10
     Dim strValue, i, x, y
     strValue = StrReverse(CStr(UCase(value)))
     For i = 0 To Len(strValue) - 1
          x = Mid(strValue, i + 1, 1)
          If Not IsNumeric(x) Then
               y = y + ((Asc(x) - 65) + 10) * (inBase ^ i)
          Else
               y = y + ((inBase ^ i) * CInt(x))
          End If
     Next
     baseN2dec = y
End Function

          

Function dec2baseN(ByVal value, ByVal outBase) As String
'Converts base 10 to any base
     Dim q 'quotient
     Dim r 'remainder
     Dim m 'denominator
     Dim y 'converted value
     m = outBase
     q = value
     Do
          r = q Mod m
          q = Int(q / m)
          If r >= 10 Then
               r = Chr(65 + (r - 10))
          End If
          y = y & CStr(r)
     Loop Until q = 0
     dec2baseN = StrReverse(y)
End Function

          

Private Sub cmdToHex_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdToHex.Click
     txtHex.Text = dec2baseN(txtDec.Text, 16)
End Sub

          

Private Sub cmdToDec_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdToDec.Click
     txtDec.Text = baseN2dec(txtHex.Text, 16)
End Sub
          

End Class