Convert Decimal fractions to binary and vice versa

V

vinod.booshanan

Hello all,

How can I convert a decimal fraction (for example 10.5) to binary form and vice versa (i.e., if I have a binary form such as 10010.011 back to decimal form)?

The DEC2BIN function in Excel works for Whole numbers and not fractions.

Please suggest!!
 
G

GS

Hello all,

How can I convert a decimal fraction (for example 10.5) to binary form and vice versa (i.e., if I have a binary form such as 10010.011 back to decimal form)?

The DEC2BIN function in Excel works for Whole numbers and not fractions.

Please suggest!!
Here's a solution posted by Rick Rothstein some years ago...

Function DecToBin(ByVal DecimalIn As Variant, Optional NumberOfBits As
Variant) As String
' The DecimalIn argument is limited to 79228162514264337593543950266
' (approximately 96-bits) - large numerical values must be entered
' as a String value to prevent conversion to scientific notation.

DecToBin = "": DecimalIn = CDec(DecimalIn)
Do While DecimalIn <> 0
DecToBin = Trim$(Str$(DecimalIn - 2 * Int(DecimalIn / 2))) & DecToBin
DecimalIn = Int(DecimalIn / 2)
Loop
If Not IsMissing(NumberOfBits) Then
If Len(DecToBin) > NumberOfBits Then
DecToBin = "Error - Number too large for bit size"
Else
DecToBin = Right$(String$(NumberOfBits, "0") & DecToBin,
NumberOfBits)
End If
End If
End Function

Function BinToDec(BinaryString As String) As Variant
' BinaryString argument can be a maximum of 96 digits (either 0's or 1's)

Dim x As Integer
Const TwoToThe48 As Variant = 281474976710656#
For x = 0 To Len(BinaryString) - 1
If x > 48 Then
BinToDec = CDec(BinToDec) + Val(Mid(BinaryString,
Len(BinaryString) - x, 1)) * TwoToThe48 * CDec(2 ^ (x - 48))
Else
BinToDec = CDec(BinToDec) + Val(Mid(BinaryString,
Len(BinaryString) - x, 1)) * CDec(2 ^ x)
End If
Next
If Len(BinToDec) > 10 Then BinToDec = CStr(BinToDec)
End Function


--
-
Garry

Free Usenet access at http://www.eternal-september.org
Classic VB Users Regroup!
comp.lang.basic.visual.misc
microsoft.public.vb.general.discussion
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top