Advertisement
2_2002-2004 String Manipulation #116365

Convert to from Binary in very little code

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

AI

AI Summary: This codebase represents a historical implementation of the logic described in the metadata. Our preservation engine analyzes the structure to provide context for modern developers.

Source Code
original-source
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
Original Comments (3)
Recovered from Wayback Machine