Guide Contents
|
DigitalDan Home Page
|
Private Function Base_To_Decimal(number As String, inBase As Integer) As DecimalError
Dim ret As DecimalError
ret.numberDecimal = 0 : ret.errorMessage = ""
number = number.ToLower
Dim digits As String = "0123456789abcdefghijklmnopqrstuvwxyz"
' validate input data
If number = "" Then
ret.errorMessage = "No number entered"
Return ret
End If
If inBase < 2 OrElse inBase > 36 Then
ret.errorMessage = "Invalid base"
Return ret
End If
' ensure number has both an integer and decimalpoint part
Dim listparts As List(Of String) = number.Split("."c).ToList
If listparts.Count = 1 Then listparts.Add("0")
If listparts.Count > 2 Then
ret.errorMessage = "Number has more than 1 decimal point"
Return ret
End If
' Process the integer part
Dim integ1 As Integer = 0
Dim dig As Integer
Dim c As Char
Dim len1 As Integer = listparts.Item(0).Length
For i As Integer = 1 To len1
c = CChar(Mid(listparts.Item(0), i, 1))
dig = digits.IndexOf(c)
If dig < 0 OrElse dig > inBase - 1 Then
ret.errorMessage = "Invalid digit in number"
Return ret
End If
integ1 += dig * CInt(Math.Round(Math.Pow(inBase, (len1 - i))))
Next
' Process after decimal point
Dim dec1 As Double = 0
len1 = listparts.Item(1).Length
For i As Integer = 1 To len1
c = CChar(Mid(listparts.Item(1), i, 1))
dig = digits.IndexOf(c)
If dig < 0 OrElse dig > inBase - 1 Then
ret.errorMessage = "Invalid digit in number"
Return ret
End If
dec1 += dig * Math.Pow(inBase, 0 - i)
Next
ret.numberDecimal = integ1 + dec1
Return ret
End Function
Public Structure DecimalError
Dim numberDecimal As Double
Dim errorMessage As String
End Structure
Private Shared Function Decimal_To_Base(number As Double, toBase As Integer) As BaseError
Dim ret As BaseError
Dim digits As String = "0123456789abcdefghijklmnopqrstuvwxyz"
ret.numberBase = "" : ret.errorMessage = ""
If toBase < 2 OrElse toBase > 36 Then
ret.errorMessage = "Invalid base"
Return ret
End If
' handle integer part
Dim integ1 As Integer = CInt(Math.Floor(number))
Dim res1 As String = ""
While integ1 > 0
res1 &= Mid(digits, 1 + (integ1 Mod toBase), 1)
integ1 \= toBase
End While
' handle after decimal point
Dim res2 As String = ""
Dim dec1 As Double = number - Int(number)
dec1 = Math.Round(dec1, 7)
' patch for rounding error in number - Int(number)
While dec1 > 0 And res2.Length < 6
dec1 *= toBase
res2 &= Mid(digits, 1 + CInt(Math.Floor(dec1)), 1)
dec1 -= CInt(Math.Floor(dec1))
End While
If res2 <> "" Then res2 = "." & res2
ret.numberBase = res1 & res2
Return ret
End Function
Public Structure BaseError
Dim numberBase As String
Dim errorMessage As String
End Structure
DigitalDan.co.uk ... Hits = 345