Online Documentation Server
 ПОИСК
ods.com.ua Web
 КАТЕГОРИИ
Home
Programming
Net technology
Unixes
Security
RFC, HOWTO
Web technology
Data bases
Other docs

 


 ПОДПИСКА

 О КОПИРАЙТАХ
Вся предоставленная на этом сервере информация собрана нами из разных источников. Если Вам кажется, что публикация каких-то документов нарушает чьи-либо авторские права, сообщите нам об этом.




Previous Table of Contents Next

To convert a number in decimal base to base a representation, we can use the following division:

Ma = [...][((srqp div a) div a) % a][(srqp div a) % a][srqp % a]

where each [] represents a digit in the new number.

This equation is schematically presented in Chapter 5, Basic Declarations and Expressions.

The decimal number 33010, will be converted to octal notation as follows:

M8 = [(330 div 8) div 8) % 8][(330 div 8) % 8][330 % 8] = [5][1][2] = 5128

Note that the parentheses are not necessary due to operator precedence rules.

The last accumulated element of the equation is the one containing the expression [z % a] where z is smaller than the base, a.

We know now the whole conversion process, so we can represent a number of any base in any other base. If the calculations are not completely clear, you should read them over again and try to use the equations to convert numbers of your choice. Reading the actual function in the script will probably make it clearer.

If the user chooses to create a base conversion table, the user is prompted to enter the highest (last) decimal number in the table, which is also equal to the number of rows + 1 (0 is included). Each value in the table is independently calculated, according to the base conversion methods explained above.

The Script

<HTML>
<HEAD>

<TITLE>Base converter</TITLE>

<SCRIPT LANGUAGE="JavaScript">
<!-- hiding content from old browsers

// Simulate the "power of" (^) operator
/////////////////////////////////////////

function power(op1, op2) {
var result = 1
for (var i = 1; i <= op2; i++) {
  result *= op1
}
return result
}

// Simulate the div (integral division)
// operator
/////////////////////////////////////////

function div(op1, op2) {
return Math.round(op1 / op2 – op1 % op2 / op2)
}

// Returns a digit (maximum hexadecimal)
// based on its decimal value
/////////////////////////////////////////

function getDigit(val) {
if (val == 10) return "A"
if (val == 11) return "B"
if (val == 12) return "C"
if (val == 13) return "D"
if (val == 14) return "E"
if (val == 15) return "F"
return val
// the return statement terminates the function,
// so there is no need for else statements
}

// Returns the decimal value of a digit
// (maximum hexadecimal)
/////////////////////////////////////////

function getValue(dig) {
if (dig == "A") return 10
if (dig == "B") return 11
if (dig == "C") return 12
if (dig == "D") return 13
if (dig == "E") return 14
if (dig == "F") return 15
return dig
// the return statement terminates the function,
// so there is no need for else statements
}

// Convert from decimal to specified base
/////////////////////////////////////////

function toBase(num, base) {
var newNum = (num == 0) ? "0" : ""
while (num >= 1) {
 newNum = getDigit(num % base) + newNum
 num = div(num, base)
}
return newNum
}

// Convert from specified base to decimal
/////////////////////////////////////////

function toDec(num, base) {
if (base == 8)
  return parseInt("0" + num)
if (base == 16)
  return parseInt("0x" + num)
num = "" + num // convert to string by casting
var numLength = num.length
// the length property returns the length of a string
var newNum = 0 // initialization
// (must be 0 so the sum is not affected)
var curDigit = ""
var contributedValueValue = 0
for (var i = numLength – 1; i >= 0; --i) {
  curDigit = num.charAt(i)
  contributedValue = getValue(curDigit)
  contributedValue *= power(base, numLength – (i + 1))
  newNum += parseInt(contributedValue)
}
 return newNum
}

// Main function that accepts input and
// calls appropriate functions
/////////////////////////////////////////
function convert(num, base1, base2) {
 if (typeof num == "string")
num = num.toUpperCase()
 if (base1 == base2)
return num
 if (base1 == 10)
return toBase(num, base2)
 if (base2 == 10)
return toDec(num, base1)
 return toBase(toDec(num, base1), base2)
}

// Create a conversion table
/////////////////////////////////////////

function drawTable(lastNum) {
with (document) {
 lastNum = parseInt(lastNum)
 write("<TABLE BORDER=3>")
 write("<TR><TD COLSPAN=8><CENTER><FONT
 COLOR=purple SIZE=+4>")
 write("Base Converter</FONT></CENTER></TD></TR>")
 write("<TR>")
 for (var k = 2; k <= 16; k = k + 2) {
   write("<TD><CENTER> Base " + k + "
  </CENTER></TD>")
 }
 write("</TR>")
 for (var i = 0; i <= lastNum; ++i) {
   write("<TR>")
   for (var j = 2; j <= 16; j = j + 2) {
write("<TD>" + toBase(i, j) + "</TD>")
  }
  write("</TR>")
 }
 write("</TABLE>")
}
}

// Gets table's input
/////////////////////////////////////////

function getTableAttributes() {
var message = "Enter last number to be converted in the table"
var lastNum = parseInt(prompt(message, 15))
if (lastNum != 0)
   drawTable(lastNum)
}
// Convert individual numbers, until the
// user selects cancel on the first
// prompt of the loop
/////////////////////////////////////////
function calcNum() {
while(1) {
 var number = prompt("Enter a number in any base:", 0)
 if (number == null)
   break
 var base1 = prompt("Enter its base:", 10)
 if (base1 == null)
 continue
 base1 = parseInt(base1)
 var base2 = prompt("Enter the desired base:", 16)
 if (base2 == null)
 continue
 base2 = parseInt(base2)
 var outputString = number + " (base " + base1 + ") = "
 outputString += convert(number, base1, base2)
 outputString += " (base " + base2 + ")"
 alert(outputString)
 }
}

// Ask user for conversion device
// (T-table, I-individual values)
/////////////////////////////////////////

function mainInput() {
 var message = "Enter (T) to create a table or (V) to "
 message += "calculate a value"
 var chosenDevice = prompt(message, "T")
 if (chosenDevice == "T" || chosenDevice == "t")
   getTableAttributes()
 else
   if (chosenDevice == "V" || chosenDevice == "v")
calcNum()
   else
alert("Goodbye!")
}
mainInput()
// end hiding content -->
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>

Example 10-2. A base converter.

Previous Table of Contents Next


With any suggestions or questions please feel free to contact us