with: Erik Oosterwal
Custom Search
|
Private Sub Dec2Bin_Click()
' Subroutine to convert floating point decimal values to floating point binary values.
'
' Written by: Erik Oosterwal
' Started on: October 26, 2005
' Completed: October 27, 2005
Dim txtNumericBaseData, txtOutputValue As String
Dim intX, intNumBits As Integer
Dim dblDecimalValue, dblFractionValue, dblBinaryFraction As Double
intNumBits = 20 ' The number of bits in the output (including the decimal point)
txtNumericBaseData = "01" ' Output digits can be either "0" or "1"
dblBinaryFraction = 0.5 ' Binary fraction bits are powers of 0.5
txtOutput.Text = "" ' Clear the display
txtOutputValue = "" ' Clear the working output variable
dblDecimalValue = Int(CDbl(txtInput.Text)) ' Get the integer portion of the input
dblFractionValue = CDbl(txtInput.Text) - dblDecimalValue ' Get the fractional portion of the input
' Figure out the integer portion of the input.
While dblDecimalValue > 0
intX = Int(((dblDecimalValue / 2) - Int(dblDecimalValue / 2)) * 2 + 1.5)
txtOutputValue = Mid(txtNumericBaseData, intX, 1) + txtOutputValue
dblDecimalValue = Int(dblDecimalValue / 2)
Wend
If txtOutputValue = "" Then txtOutputValue = "0" ' If there was no whole number, set it to "0"
txtOutputValue = txtOutputValue + "." ' then add a decimal point
' Figure out the fractional portion of the input.
While Len(txtOutputValue) < intNumBits And dblFractionValue > 0 ' As long as we're not exceeding the
' allowed number of bits in the output
' and there's still part of the input
' value to be converted...
If dblFractionValue >= dblBinaryFraction Then ' If the input number is larger than the fraction bit,
txtOutputValue = txtOutputValue + "1" ' add a "1" to the output and
dblFractionValue = dblFractionValue - dblBinaryFraction ' reduce the input number by the fraction bit's value.
Else ' Otherwise...
txtOutputValue = txtOutputValue + "0" ' just tag on a "0" to the end of the output.
End If
dblBinaryFraction = dblBinaryFraction / 2# ' The fraction bit must be cut in half.
Wend
txtOutput.Text = txtOutputValue ' Send the output value to the display.
End Sub
For a more generalized routine that can convert integer values between any
two numeric bases, see the Numeric Base
Conversion article from the main Computer
Science 101 page.
You can also download a zip file that contains
the listing given above as well as an executable file that demonstrates this
routine.