by MrEnigma (8 Submissions)
Category: String Manipulation
Compatability: Visual Basic 3.0
Difficulty: Intermediate
Date Added: Wed 3rd February 2021
Rating: (2 Votes)
Here is are two nice functions that will convert Decimal values to binary and binary to decimal in a surprisingly short amount of code.
Comments welcome. Please
Public Function DecimalToBinary(sValue As String) As String
Dim i As Integer
Const sTable As String = "0000,0001,0010,0011,0100,0101,0110,0111,1000,1001,1010,1011,1100,1101,1110,1111"
Dim asBinTable() As String
Dim sHexValue As String
If Len(sValue) > 9 Then
' the HEX Function cannot handle larger numbers
Exit Function
End If
DecimalToBinary = ""
' Set up the Binary Table
asBinTable = Split(sTable, ",")
sHexValue = Hex(Val(sValue))
For i = 1 To Len(sHexValue)
DecimalToBinary = DecimalToBinary & asBinTable(Val("&H" & Mid$(sHexValue, i, 1)))
Next
End Function
Public Function BinaryToDecimal(sBinary As String) As String
Dim i As Integer
BinaryToDecimal = 0
If Len(sBinary) > 49 Then
' Binary numbers larger than 49 bits
' Will return an Error E+
Exit Function
End If
For i = 0 To Len(sBinary) - 1
If Mid$(sBinary, Len(sBinary) - i, 1) Then
BinaryToDecimal = BinaryToDecimal + 2 ^ i
End If
Next
End Function