These are all good explanations, but still, this code raises questions.... the binary equivalents are still equal..

VB Code:
  1. Private Sub Command1_Click()
  2. Dim aa1 As Double
  3. Dim aa2 As Double
  4. Dim bb As Double
  5.  
  6. Dim aa As Double
  7.  
  8. aa1 = 1.36
  9. aa2 = 0.04
  10.  
  11. aa = aa1 + aa2
  12.  
  13. bb = 1.4
  14. Debug.Print ("bb= " & Num2Bin(bb))
  15. Debug.Print ("aa1=" & Num2Bin(aa1))
  16. Debug.Print ("aa2=" & Num2Bin(aa2))
  17. Debug.Print ("aa= " & Num2Bin(aa))
  18. Debug.Print ("1.4=" & Num2Bin(1.4))
  19. If aa > bb Then
  20. MsgBox aa & ">" & bb
  21. ElseIf aa = bb Then
  22. MsgBox aa & "=" & bb
  23. Else
  24. MsgBox aa & "<" & bb
  25. End If
  26. End Sub
  27.  
  28.  
  29. Public Function Num2Bin(ByVal q As Variant, _
  30. Optional ByVal Precision As Integer = 13) As String
  31.  
  32. 'Declarations
  33. Dim ln2 As Double 'Cache the value of Log(2)
  34. Dim sResult As String 'Temp variable to hold the result
  35. Dim fStart As Boolean 'Flag to indicate if we have started the number
  36. Dim i As Long
  37. Dim l As Long
  38. Dim qL As Long, qD As Double
  39.  
  40. 'Implementation
  41. If IsNumeric(q) Then
  42.  
  43. 'Cache this value, it's very useful!
  44. ln2 = Log(2)
  45.  
  46. 'Don't use Int(...), as this limits the range to integers
  47. i = Log(q) / ln2
  48.  
  49. If i > 30 Then
  50. 'Overflow
  51.  
  52. Err.Raise 6, "Num2Bin", "Overflow"
  53.  
  54. Else
  55.  
  56. 'Bitwise operators use CLng on the operands
  57. 'e.g. 0.75 And 1 = 1
  58. 'To get around this, use a Long copy of q
  59. 'and check for rounding up
  60. qL = CLng(q)
  61.  
  62. If qL > q Then qL = qL - 1
  63.  
  64. Do While i >= 0
  65.  
  66. l = Exp(i * ln2)
  67.  
  68. If (qL And l) Then
  69.   sResult = sResult & "1"
  70.   qL = qL - l
  71.   q = q - l
  72.   'Have started the number
  73.   fStart = True
  74. ElseIf fStart Then
  75.   'Do not write leading zeros
  76.   'This is needed because CLng(Log(q) / Log(2))
  77.   'may round up.
  78.   sResult = sResult & "0"
  79. End If
  80.  
  81. i = i - 1
  82.  
  83. Loop
  84.  
  85. 'If we haven't got a value yet, the integer part is 0
  86. If sResult = vbNullString Then sResult = "0"
  87.  
  88. If q > 0 And Precision > 0 Then
  89. 'Need to deal with fractional part
  90. sResult = sResult & "."
  91. i = -1
  92.  
  93. 'Convert q to a double
  94. qD = CDbl(q)
  95.  
  96. 'Stop when q=0 or have reached max precision
  97. Do While qD > 0 And Precision > 0
  98. qD = qD * 2
  99. If Int(qD) = 1 Then
  100. sResult = sResult & "1"
  101. qD = qD - 1
  102. Else
  103. sResult = sResult & "0"
  104. End If
  105.  
  106. i = i - 1
  107. Precision = Precision - 1
  108. Loop
  109. End If
  110.  
  111. Num2Bin = sResult
  112. End If
  113. Else
  114. 'q is not numeric
  115. Err.Raise 13, "Num2Bin", "Type Mismatch"
  116. End If
  117. End Function