dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: Visual Basic
Expertise: Beginner
Mar 23, 2000

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


Convert a Decimal Number to Base N

Here's a function that converts a decimal number (base 10) to another base number system. Each digit position corresponds to a power of N, where N is a number between 2 and 36. In other words, if a number system's base is N, then N digits are used to write numbers in that system. For example, the base 2 number system (binary) uses the digits 0 and 1, while the base 20 system uses digits 0 through K.

The ConvertDecToBaseN function accepts a double-value decimal number and a byte-value representing the base number between 2 and 36. By default, the base value used is 16 (hexadecimal). The decimal number is converted to a positive number if it's negative. This function is useful for representing large numbers as strings, using fewer digit positions. I developed it to help reduce the footprint of several large numbers used in constructing a 16-character unique string ID. (Creating a complementary function to convert a base N number back into a decimal would be a great exercise.)
 
Public Function ConvertDecToBaseN(ByVal dValue As Double, _
	Optional ByVal byBase As Byte = 16) As String
	Const BASENUMBERS As String = _
		"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	Dim sResult As String
	Dim dRemainder As Double
	On Error GoTo ErrorHandler
	sResult = ""
	If (byBase < 2) Or (byBase > 36) Then GoTo Done
	dValue = Abs(dValue)
Do
	dRemainder = dValue - (byBase * Int((dValue / byBase)))
	sResult = Mid$(BASENUMBERS, dRemainder + 1, 1) & sResult
	dValue = Int(dValue / byBase)
Loop While (dValue > 0)
Done:
	ConvertDecToBaseN = sResult
	Exit Function
ErrorHandler:
	Err.Raise Err.Number, "ConvertDecToBaseN", _
		Err.Description
End Function
Sample usage:
ConvertDecToBaseN(999999999999#, 36)
'Returns 'CRE66I9R
Peter Rodriguez
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date