penagate
Jul 8th, 2005, 12:17 PM
I recently felt the need too display some numbers in binary, and after getting sick of working it out on paper, this function was born (I completely forgot you can use the Windows calculator :p) And just now I added the facility to display the binary output of strings as well.
To call it just pass either a string or number and optionally a fixed length for the output
Public Function DumpBits(ByRef pValue As Variant, Optional ByVal lLenDesired As Long = -1) As String
Dim chBuffer() As Byte
Dim i As Long
Dim j As Long
If (VarType(pValue) = vbString) Then
If (lLenDesired < 1) Then lLenDesired = Len(pValue) * 2
ReDim chBuffer(lLenDesired)
chBuffer = pValue
For i = UBound(chBuffer) To 0 Step -1
For j = 1 To 8
DumpBits = CStr(Abs((chBuffer(i) And (2 ^ (j - 1))) > 0)) & DumpBits
Next j
Next i
Else
If (lLenDesired < 1) Then
lLenDesired = 0
Do While (pValue \ (2 ^ lLenDesired)) > 0
lLenDesired = lLenDesired + 1
Loop
End If
For i = 1 To lLenDesired
DumpBits = CStr(Abs((pValue And (2 ^ (i - 1))) > 0)) & DumpBits
Next i
End If
If (Len(DumpBits) > lLenDesired) Then
Do While Left$(DumpBits, 1) = "0" And Len(DumpBits) > lLenDesired
DumpBits = Right$(DumpBits, Len(DumpBits) - 1)
Loop
ElseIf (Len(DumpBits) < lLenDesired) Then
Do While Len(DumpBits) < lLenDesired
DumpBits = "0" & DumpBits
Loop
End If
End Function
To call it just pass either a string or number and optionally a fixed length for the output
Public Function DumpBits(ByRef pValue As Variant, Optional ByVal lLenDesired As Long = -1) As String
Dim chBuffer() As Byte
Dim i As Long
Dim j As Long
If (VarType(pValue) = vbString) Then
If (lLenDesired < 1) Then lLenDesired = Len(pValue) * 2
ReDim chBuffer(lLenDesired)
chBuffer = pValue
For i = UBound(chBuffer) To 0 Step -1
For j = 1 To 8
DumpBits = CStr(Abs((chBuffer(i) And (2 ^ (j - 1))) > 0)) & DumpBits
Next j
Next i
Else
If (lLenDesired < 1) Then
lLenDesired = 0
Do While (pValue \ (2 ^ lLenDesired)) > 0
lLenDesired = lLenDesired + 1
Loop
End If
For i = 1 To lLenDesired
DumpBits = CStr(Abs((pValue And (2 ^ (i - 1))) > 0)) & DumpBits
Next i
End If
If (Len(DumpBits) > lLenDesired) Then
Do While Left$(DumpBits, 1) = "0" And Len(DumpBits) > lLenDesired
DumpBits = Right$(DumpBits, Len(DumpBits) - 1)
Loop
ElseIf (Len(DumpBits) < lLenDesired) Then
Do While Len(DumpBits) < lLenDesired
DumpBits = "0" & DumpBits
Loop
End If
End Function