# Base Conversion Functions

Home

Thanks to Planet Source Code for these useful functions.

```Public Function Bin2Dec(ByVal sBin As String) As Double

Dim i As Integer

For i = 1 To Len(sBin)
Bin2Dec = Bin2Dec + CDbl(CInt(Mid(sBin, Len(sBin) - i + 1, 1)) * 2 ^ (i - 1))
Next i

End Function

Public Function BigDecToHex(ByVal DecNum) As String

' This function is 100% accurate untill 15,000,000,000,000,000 (1.5E+16)

Dim NextHexDigit As Double
Dim HexNum As String

HexNum = ""
While DecNum <> 0
NextHexDigit = DecNum - (Int(DecNum / 16) * 16)

If NextHexDigit < 10 Then
HexNum = Chr(Asc(NextHexDigit)) & HexNum
Else
HexNum = Chr(Asc("A") + NextHexDigit - 10) & HexNum
End If
DecNum = Int(DecNum / 16)
Wend
If HexNum = "" Then HexNum = "0"
BigDecToHex = HexNum

End Function

Public Function Bin2Hex(ByVal sBin As String) As String

Dim i As Integer
Dim nDec As Long

sBin = String(4 - Len(sBin) Mod 4, "0") & sBin 'Add zero To complete Byte
For i = 1 To Len(sBin)
nDec = nDec + CInt(Mid(sBin, Len(sBin) - i + 1, 1)) * 2 ^ (i - 1)
Next i
Bin2Hex = Hex(nDec)
If Len(Bin2Hex) Mod 2 = 1 Then Bin2Hex = "0" & Bin2Hex

End Function

Public Function Dec2Bin(ByVal nDec As Integer) As String

'This function is the same then Hex2Bin,
'but it has been copied to speed up process
Dim i As Integer
Dim j As Integer
Dim sHex As String
Const HexChar As String = "0123456789ABCDEF"

sHex = Hex(nDec) 'That the only part that is different

For i = 1 To Len(sHex)
nDec = InStr(1, HexChar, Mid(sHex, i, 1)) - 1

For j = 3 To 0 Step -1
Dec2Bin = Dec2Bin & nDec \ 2 ^ j
nDec = nDec Mod 2 ^ j
Next j
Next i
'Remove the first unused 0
i = InStr(1, Dec2Bin, "1")
If i <> 0 Then Dec2Bin = Mid(Dec2Bin, i)

End Function

Public Function Hex2Bin(ByVal sHex As String) As String

Dim i As Integer
Dim j As Integer
Dim nDec As Long
Const HexChar As String = "0123456789ABCDEF"

For i = 1 To Len(sHex)
nDec = InStr(1, HexChar, Mid(sHex, i, 1)) - 1

For j = 3 To 0 Step -1
Hex2Bin = Hex2Bin & nDec \ 2 ^ j
nDec = nDec Mod 2 ^ j
Next j
Next i
'Remove the first unused 0
i = InStr(1, Hex2Bin, "1")
If i <> 0 Then Hex2Bin = Mid(Hex2Bin, i)

End Function

Public Function Hex2Dec(ByVal sHex As String) As Long

Dim i As Integer
Dim nDec As Long
Const HexChar As String = "0123456789ABCDEF"

For i = Len(sHex) To 1 Step -1
nDec = nDec + (InStr(1, HexChar, Mid(sHex, i, 1)) - 1) * 16 ^ (Len(sHex) - i)
Next i
Hex2Dec = CStr(nDec)

End Function```