|
-
May 24th, 2003, 02:30 PM
#1
Thread Starter
New Member
VB - Convert Decimal Values to Various Bases
This is a function I wrote a while back. There are many ways to convert decimal to binary, and several have already been posted, but I really like this algorithm that I wrote. I was trying to go for a KISS approach here, but feel free to make it more professional.
VB Code:
Public Function ChangeBase(N As Long, NewBase As Integer) As String
Dim K As Long
Dim L As Long
Do
K = N \ NewBase
L = N - (K * NewBase)
N = K
ChangeBase = L & ChangeBase
DoEvents
Loop Until K < NewBase
ChangeBase = K & ChangeBase
End Function
This will convert a decimal value to base 2, 3, 4, 5... whatever. However, if you want to convert to a base above base 10, you'll have to write some sort of code to catch values above 10 and convert them to a letter in the alphabet.
Last edited by Tito; May 24th, 2003 at 02:43 PM.
-
Jun 23rd, 2003, 06:11 AM
#2
PowerPoster
Here's how to convert any base to any other base:
VB Code:
Public Function ChangeBase(iNumber As Double, iFromBase As Long, iToBase As Long) As Double
On Error GoTo 1
Dim A As Long
Dim Temp As String
Dim Length As Long
Dim Number As Long
Dim Base10 As Long
Dim Result As Long
Dim Minus As Long
Dim Floating As Double
'Get floating part
Floating = iNumber - Int(iNumber)
If Floating > 0 Then: Floating = iToBase / (iFromBase / Floating)
'Pre-check base
Minus = Sgn(iNumber)
If iFromBase = 10 Then
Base10 = Abs(CLng(iNumber))
Else
'Get number string
Temp = CStr(Abs(CLng(iNumber)))
Length = Len(Temp)
'Convert to 10-base
For A = 0 To Length - 1
'Check symbol
Number = CLng(Mid(Temp, Length - A, 1))
'Add to result
Base10 = Base10 + (iFromBase ^ A) * Number
Next
End If
'Pre-check base
If iToBase = 10 Then
ChangeBase = Minus * (CDbl(Base10) + Floating)
Exit Function
End If
'Convert to new base
Length = 0
While Base10 > 0
If Base10 < iToBase Then
'Last part
Result = Result + (10 ^ Length) * Base10
Base10 = 0
Else
'Get value
Number = Base10 Mod iToBase
Result = Result + (10 ^ Length) * Number
Base10 = Int(Base10 / iToBase)
End If
'Next 10-factor
Length = Length + 1
Wend
'Return result
ChangeBase = Minus * (CDbl(Result) + Floating)
Exit Function
1 'Error
End Function
[edit]Added support for negative and floating point numbers[/edit]
Last edited by Fox; Jun 23rd, 2003 at 07:30 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|