When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips

Sections:
Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
XML Info
Information:
Feedback
Author an Article
ASP ASP.NET ASP FAQs Message Board Feedback
Print this page.
Published: Friday, March 24, 2000

Converting from Base N to Base X

By Alex Morgan and Claude Rubinson


VBScript does not natively support Base N notation or calculations; nevertheless, since both SQL and COM objects support Base N, the ability to convert from decimal (Base 10) format to Base N (and vice versa) is sometimes necessary.

- continued -

Three scripts are developed below. The first converts from Base N to decimal. The second, from decimal to Base N. The third utilizes the previous functions to permit conversion between any two bases (Base N to Base X).

There are a few issues to be aware of. First, the scripts are case-insensitive. Specifically, all lower-case characters are converted to upper-case before being processed. Second, the supplied value may be specified either as numeric or text (just be sure to include the quotes when specifying values as text!). Third, the inBase and outBase must be specified as integers. Base A would be specified as 10; Base B, as 11; etc. Finally, the scripts have an upperbound limit of Base Z. Please note that we have not included error-trapping in these functions; you may wish to.

Happy Programming!

<%
Function baseN2dec(value,inBase)
'Converts any base to base 10

	dim strValue, i, x, y

	strValue = StrReverse(CStr(UCase(value)))

	for i = 0 to len(strValue)-1
		x = mid(strValue,i+1,1)
		if NOT isNumeric(x) then
			y = y + ((Asc(x) - 65) + 10) * (inBase ^ i)
		else
			y = y + ((inBase ^ i) * CInt(x))
		end if
	next

	baseN2dec = y

End Function


Function dec2baseN(value,outBase)
'Converts base 10 to any base

	dim q 'quotient
	dim r 'remainder
	dim m 'denominator
	dim y 'converted value

	m = outBase
	q = value

	do
		r = q Mod m
		q = Int(q/m)
	
		if r >= 10 then
			r = Chr(65 + (r-10))
		end if
	
		y = y & CStr(r)
				
	loop until q = 0
	
	dec2baseN = StrReverse(y)

End Function

Function baseN2baseX(value,inBase,outBase)

	baseN2baseX = dec2baseN(baseN2dec(value,inBase),outBase)

End Function
%>


ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article