dh-Materialien
JavaScript Programme
 

Umrechnen von Zahlen


decToAnyBase ( , )

  z  bpot bpot <= z code ziffer ergebnis bpot > 1
0 2005 16 true 0     true

// DecToAnyBase (c)2007 dh

var rows = 1;
var o = new Array(8);
var oNode = new Array(8);
var dnum = 0;
var b = 0;

o[0] = "0";    // Schritt
o[1] = "2005"; // z
o[2] = "2";    // bpot
o[3] = "true"; // bpot <= z
o[4] = "0";    // code
o[5] = "";     // ziffer
o[6] = "";     // ergebnis
o[7] = "true"; // bpot > 1

function DecToAnyBase (dnum, b) {
   var bpot = b;
   var z = dnum;
   var code = 0;
   var ziffer = ""
   var ergebnis = "";

   while (bpot <= z) {
      bpot = bpot*b;
      o[0] = ""+rows;
      o[2] = ""+bpot;
      if (bpot > z) o[3] = "false";
   }

   do {
      bpot = bpot/b;
      code = Math.floor(z/bpot);
      // 10 -> A; 11 -> B; u.s.w.
      var codeplus55 = String.fromCharCode(code + 55);
      var codeplus48 = String.fromCharCode(code + 48);
      ziffer = (code > 9) ? codeplus55 : codeplus48;
      ergebnis = ergebnis + ziffer;
      z = z - code*bpot;

      o[0] = ""+rows;
      o[1] = ""+z;
      o[2] = ""+bpot;
      o[4] = ""+code;
      o[5] = ""+ziffer;
      o[6] = ""+ergebnis;
      o[7] = (bpot > 1) ? "true" : "false";
      newRow();

   } while (bpot > 1);

   return ergebnis;
}

function calc() {
   while (rows > 0) {
      document.getElementById("tab").deleteRow(rows);
      rows--;
   }

   dnum = 1*document.getElementById("e_dnum").value;
   b = 1*document.getElementById("e_b").value;

   if (dnum < 0) {
      dnum = 0; document.getElementById("e_dnum").value = "0";
   }
   if (b > 36) {
      b = 36; document.getElementById("e_b").value = "36";
   }
   if (b < 2) {
      b = 2; document.getElementById("e_b").value = "2";
   }

   o[0] = "0";
   o[1] = ""+dnum;
   o[2] = ""+b;
   o[3] = (b <= dnum) ? "true" : "false";
   o[4] = "0";
   o[5] = "";
   o[6] = "";
   o[7] = "true";
   newRow();
   ergebnis = DecToAnyBase (dnum, b);
   ausgabe ("resultat", dnum + " [10] = " + ergebnis + " [" + b + "]");
}

function newRow() {
   rows++;
   otd = new Array(8);
   for (n=0; n<8; n++) {
      otd[n] = document.createElement("td");
      otd[n].align="right";
      oNode[n] = document.createTextNode(o[n]);
      otd[n].appendChild(oNode[n]);
   }
   row = document.getElementById("tab").insertRow(rows);
   for (n=0; n<8; n++) row.appendChild(otd[n]);
}

var defaultNode = document.createTextNode("");
function ausgabe (ST, out) {
// gibt den Wert von out an einer bestimmten Stelle im Dokument aus

   with (document.getElementById (ST)) {
      outNode = document.createTextNode("");
      appendChild (defaultNode);
      replaceChild (outNode, document.getElementById(ST).firstChild);
      outNode = document.createTextNode(out);
      appendChild (defaultNode);
      replaceChild (outNode, document.getElementById(ST).firstChild);
   }
}

Das Umrechnen von Zahlen