To read the article online, visit http://www.4GuysFromRolla.com/webtech/032400-1.shtml

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.

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
%>


Article Information
Article Title: Converting from Base N to Base X
Article Author: Alex Morgan and Claude Rubinson
Published Date: Friday, March 24, 2000
Article URL: http://www.4GuysFromRolla.com/webtech/032400-1.shtml


Copyright 2017 QuinStreet Inc. All Rights Reserved.
Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers