Javascript
Numeric Base Conversion

By David R. Tribble
Revision 1.1, 2008-04-08


Description

The JavaScript code below displays a form for converting a numeric value from decimal (base 10) to another base or vice versa.

Notes

The Zconvert function does all the work of converting the input value into a number (which JavaScript stores internally as a floating-point value) and then converting that number into the output value of the selected number base. This function is invoked by the ZconvertTo function, which is triggered by the "Decimal » Base" button, and the ZconvertFrom function, which is triggered by the "Base » Decimal" button.

As a validation, the resulting output value is converted back to the input number base, and that result is compared to the original input value. If they do not match, it is assumed that numeric overflow has occurred during the conversion, and the literal value "OVERFLOW" is displayed as the result. Note that only a minimal amount of validation is performed on the input value, so malformed numbers will produce unexpected results.

Rendered Appearance

Decimal:
Base:
Result:

Source Code

<noscript>
 <font color='#CF0000'>
 <b>You do not have JavaScript enabled in your browser.</b>
 </font>
</noscript>

<!-- =============================== -->
<p align="center">
<!-- The conversion panel -->
<table id="ZDConversion" cols="2" rows="5" border="0" width="550px"
   bgcolor="#F0F0FF">
 <!-- Input value -->
 <tr>
  <th width="20%" align="right"> Decimal: </th>
  <td>
   <input id="ZIinput" type="text" value="+0" size="24" maxlength="21"
      style="background:#F0FFF0"/>
  </td>
 </tr>

 <!-- Numeric base -->
 <tr>
  <th align="right"> Base: </th>
  <td>
   <select id="ZIbase" style="background:#F0FFF0">
     <option value= "2">2 &nbsp; Binary</option>
     <option value= "3">3 &nbsp; Trinary</option>
     <option value= "4">4</option>
     <option value= "5">5</option>
     <option value= "6">6</option>
     <option value= "7">7</option>
     <option value= "8">8 &nbsp; Octal</option>
     <option value= "9">9</option>
     <option value="10" selected="selected">10 &nbsp; Decimal</option>
     <option value="11">11</option>
     <option value="12">12 &nbsp; Duodecimal</option>
     <option value="13">13</option>
     <option value="14">14</option>
     <option value="15">15</option>
     <option value="16">16 &nbsp; Hexadecimal</option>
     <option value="17">17</option>
     <option value="18">18</option>
     <option value="19">19</option>
     <option value="20">20</option>
     <option value="21">21</option>
     <option value="22">22</option>
     <option value="23">23</option>
     <option value="24">24</option>
     <option value="25">25</option>
     <option value="26">26</option>
     <option value="27">27</option>
     <option value="28">28</option>
     <option value="29">29</option>
     <option value="30">30</option>
     <option value="31">31</option>
     <option value="32">32</option>
     <option value="33">33</option>
     <option value="34">34</option>
     <option value="35">35</option>
     <option value="36">36</option>
   </select>
  </td>
 </tr>

 <!-- Output value -->
 <tr>
  <th align="right"> Result: </th>
  <td>
   <input id="ZIoutput" type="text" value="+0" size="65"
      style="background:#F0FFF0"/>
  </td>
 </tr>
</table> <!-- ZDConversion -->

<!-- Buttons -->
<table cols="2" rows="2" border="0" width="550px">
 <tr>
  <!-- Conversion buttons -->
  <td width="50%" align="left">
    <input type="button" style="background:#A0C0E0"
      value="Decimal &#187; Base"
      title="Convert from decimal"
      onclick="ZconvertTo(ZIinput.value, ZIbase.value, ZIoutput)"/>
    <input type="button" style="background:#A0C0E0"
      value="Base &#187; Decimal"
      title="Convert to decimal"
      onclick="ZconvertFrom(ZIoutput.value, ZIbase.value, ZIinput)"/>
  </td>
  <!-- Reset button -->
  <td align="right">
    <input type="button" style="background:#A0C0E0" value="Reset"
      title="Reset to today's date" onclick="Zreset(ZIinput, ZIoutput)"/>
  </td>
 </tr>
</table>
</p>
<script type="text/javascript" language="JavaScript">
//<!--
// jsconvert.html
//
// This is known to work with:
//   FireFox 2.0
//   MS Internet Explorer 6.0
//
// Copyright ©2008 by David R. Tribble, all rights reserved.
// Permission is granted to anyone except members of organizations designated
// as terrorist organizations by the U.S. State Department to freely use,
// duplicate, and modify this source code.

var Zinfo = new Object();
Zinfo.digits =
  [
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
    "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
    "U", "V", "W", "X", "Y", "Z"
  ];

function ZdigitToInt(ch)
{
  for (var i = 0;  i < Zinfo.digits.length;  i++)
    if (ch == Zinfo.digits[i])
      return (i - 0);
  return 0;
}

function Zconvert(v, from, to)
{
  try
  {
    // Parse input value
    var sign = v.substr(0, 1);
    if (sign == "+"  ||  sign == "-")
      v = v.substr(1);
    else
      sign = "";

    // Convert the input value to a number in the input base
    var r = 0;
    while (v != "")
    {
        var d = v.substr(0, 1);
        d = ZdigitToInt(d);
        v = v.substr(1);
        r = r*from + d;
    }
    v = r;

    // Convert the number to the output base
    r = "";
    do
    {
        var d = Math.round(v%to, 0);
        v = Math.round((v - d)/to, 0);
        r = Zinfo.digits[d] + r;
    } while (v > 0);

    r = sign + r;
    return r;
  }
  catch (ex)
  {
    alert("Error for: '" + v + "'");
    return 0;
  }
}

function ZcleanIt(v)
{
  // Clean up the input value
  v = v.replace(/[ ,]+/g, '');
  v = v.toUpperCase();
  var p = v.indexOf(".");
  if (p >= 0)
    v = v.substr(0, p);
  p = v.substr(0, 1);
  if (p == "+"  ||  p == "-")
    v = v.substr(1);
  else
    p = "";
  v = v.replace(/^0+/, '');
  v = p + v;
  if (v == "")
    v = "0";
  return v;
}

function ZconvertTo(v, base, res)
{
  // Clean up the input value
  v = ZcleanIt(v);

  // Convert the numeric value
  var r = Zconvert(v, 10, base);
  var c = Zconvert(r, base, 10);
  if (c != v)
    r = "OVERFLOW";
  res.value = r;
}

function ZconvertFrom(v, base, res)
{
  // Clean up the input value
  v = ZcleanIt(v);

  // Convert the numeric value
  var r = Zconvert(v, base, 10);
  var c = Zconvert(r, 10, base);
  if (c != v)
    r = "OVERFLOW";
  res.value = r;
}

function Zreset(inp, out)
{
  // User clicked the "Reset" button
  inp.value = "+0";
  out.value = "+0";
}
//-->
</script>


Copyright ©2008 by David R. Tribble, all rights reserved.
Permission is granted to anyone to link to this document and to quote portions of it without restriction.
Permission is granted to anyone except members of organizations designated as terrorist organizations by the U.S. State Department to freely use, duplicate, and modify the source code.