Zahlenkonversion

Quelltext von numconvert.js

Im folgenden Quelltext sind Funktionsdeklarationen rot und Kommentare grün markiert.
var B36Str="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

function ConvertNumber(x,y)
/* wandelt Zahl x in
     y=2: binaere
     y=3: ternaere
     y=4: quartaere
     ...
     y=16: hexadezimale
     ...
     y=36: auf Basis 36 beruhende
   Darstellung um */
{
  var a=Math.round(Number(x)),n=Math.round(Number(y)),b,zahl="",vz="";
  if (a==0)
    return "0";
  if ((n<2)||(n>36))
    return "keine Darstellung auf der Basis "+y+" verfuegbar";
  if (a<0)
  {
    vz="-";
    a=-a;
  }
  while (a>0.5)
  {
    b=a%n;
    zahl=B36Str.charAt(b)+zahl;
    a=Math.floor(a/n+0.001);
  }
  return vz+zahl;
}

function CharToNumber(c)
/* wandelt einen Zeichencode in eine Zahl um */
{
  if (c>96) /* Ziffern "a".."f"; "a"=97 */
    return c-87;
  if (c>64) /* Ziffern "A".."F"; "A"=65 */
    return c-55;
  if (c>47) /* Ziffern "0".."9"; "0"=48 */
    return c-48;
  return -1;
}

function ConvertToNumber(x,y)
/* wandelt Zeichenkette x von
     y=2: binaerer
     y=3: ternaerer
     y=4: quartaerer
     ...
     y=16: hexadezimaler
     ...
     y=36: auf Basis 36 beruhender
   Darstellung in eine Zahl um */
{
  var n=Math.round(Number(y)),zahl=0,faktor=1,i=0,ziffer;
  if ((n<2)||(n>36))
    return "keine Umwandlung auf der Basis "+y+" verfuegbar";
  if (x.charAt(0)=="-")
  {
    faktor=-1;
    i=1;
  }
  while (i<x.length)
  {
    zahl=zahl*n;
    ziffer=CharToNumber(x.charCodeAt(i));
    zahl+=ziffer;
    i++;
    if ((ziffer<0)||(ziffer>=n))
      return "Ziffer \""+x.charAt(i-1)+"\" (Zeichen Nummer "+i+") ist nicht im gueltigen Bereich";
  }
  return faktor*zahl;
}
Autor: Ulrich Kritzner