by Craig Hillsdon (7 Submissions)
Category: String Manipulation
Compatability: VB 6.0
Difficulty: Unknown Difficulty
Originally Published: Thu 24th August 2000
Date Added: Mon 8th February 2021
Rating: (1 Votes)
Convert Decimal to Binary, Binary to Decimal, and Hexadecimal to Decimal. Three functions with three example procedures to call them including
API Declarations
This code was actually written as an Excel 97 macro.
decout = 0
bits = Len(mybin)
'convert binary to decimal
For i = 1 To bits
If Mid(mybin, i, 1) = "1" Then
decout = decout + (2 ^ bits) / 2
ElseIf Mid(mybin, i, 1) <> "0" Then
MsgBox "Invalid input", , "Error"
decout = -1
Exit Function
End If
bits = bits - 1
Next i
End Function
Sub convertBin2Dec()
Dim decout As Long
Dim mybin As String
mybin = InputBox("Decimal")
Binary2Decimal mybin, decout
If decout <> -1 Then MsgBox decout
End Sub
Function Decimal2Binary(mynum As Long, binout As String)
Dim bit() As Integer
Dim bits As Integer
binout = ""
'find out how big the number is in bits
x = 1
bits = 1
Do While mynum > x
x = x * 2
bits = bits + 1
Loop
bits = bits - 1
'redim 'bit' to number of bits
ReDim bit(1 To bits)
'convert decimal to binary
For i = 1 To bits
If mynum > ((2 ^ bits) / 2) - 1 Then
bit(i) = "1"
mynum = mynum - ((2 ^ bits) / 2)
Else
bit(i) = "0"
End If
binout = binout & bit(i)
bits = bits - 1
Next i
End Function
Sub convertDec2Bin()
Dim binout As String
Dim mynum As Long
On Error GoTo azkaban
mynum = InputBox("Decimal")
Decimal2Binary mynum, binout
MsgBox binout
'the output from Decimal2Binary only uses as many 'bits' as it needs,
'i.e. all leading zeros are removed (actually, they are never there
'in the first place). if you want the output in, for example, 8 bits,
'you could use the following line of code to reformat the output:
'binout = String(8 - Len(binout), "0") & binout '8 is number of bits
Exit Sub
azkaban:
MsgBox "Invalid input", , "Error"
End Sub
Function Hexadecimal2Decimal(myhex As String, decout As Long)
myhex = UCase(myhex)
multiplier = 1
decout = 0
hexstr = "0123456789ABCDEF"
For i = Len(myhex) To 1 Step -1
z = Mid(myhex, i, 1)
v = Val(InStr(1, hexstr, z)) - 1
If v + 1 = 0 Then
MsgBox "Invalid input", , "Error"
decout = -1
Exit Function
End If
decout = decout + v * multiplier
multiplier = multiplier * 16
Next i
End Function
Sub convertHex2Dec()
Dim decout As Long
Dim myhex As String
myhex = InputBox("Hexadecimal")
Hexadecimal2Decimal myhex, decout
If decout <> -1 Then MsgBox decout
End Sub
No comments have been posted about Convert Decimal to Binary, Binary to Decimal, and Hexadecimal to Decimal. Three functions with thre. Why not be the first to post a comment about Convert Decimal to Binary, Binary to Decimal, and Hexadecimal to Decimal. Three functions with thre.