I fixed it a bit...
Printable View
I fixed it a bit...
This is a 5 year old post, but how about this very short function:
This perhaps better matching with Hex and Oct, that use a feature of Oct() with 32-bit 2's complement for negative numbers:Code:Function Dec2Bin(ByVal Num As Long) As String
Select Case Num
Case Is > 1: Dec2Bin = Dec2Bin(Num \ 2) & (Num Mod 2)
Case 0, 1: Dec2Bin = Num
Case Else: Dec2Bin = -Dec2Bin(-Num)
End Select
End Function
Code:Function Bin(ByVal Num As Long) As String
Dim O2B As Variant, sOct As String, i As Long
If Num = 0 Then Bin = "0": Exit Function
O2B = Array("000", "001", "010", "011", "100", "101", "110", "111")
sOct = Oct$(Num)
Bin = Space$(3 * Len(sOct))
For i = 1 To Len(sOct)
Mid$(Bin, (i - 1) * 3 + 1, 3) = O2B(Mid$(sOct, i, 1))
Next
Bin = Mid$(Bin, InStr(Bin, "1"))
End Function
here is another method that may not be as good, but is pretty simple and not recursive if that is an advantage
Code:Function binn(dnum As Long) As String
If dnum = 0 Then binn = 0: Exit Function
Dim bnum As String
i = 0
Do While dnum \ 2 ^ i >= 1
bnum = Abs((dnum And 2 ^ i) = 2 ^ i) & bnum
i = i + 1
Loop
binn = bnum
End Function