Basically a decimal-binary conversion. Code follows:
function convert() {
var val = $("txtIn").value;
if (val ===""){
alert("No value entered for converstion.");
return;
}
var cT = document.getElementsByName("tType");
if (cT[0].checked) {
//to Binary
var dval = parseInt(val);
if (isNaN(dval)) {
alert("Input value is not a number!");
} else if ((val % 1) !==0) {
alert("Input value cannot include fraction or decimal");
} else if (dval < 0) {
alert("Input value must be a positive value.");
} else {
convertByArray(dval);
}
} ***else if (cT[1].checked)*** {
//to decimal
var bval = parseInt(val,2);
if (isNaN(bval)) {
alert("Input value is not a number!");
} else if ((val % 1) !==0) {
alert("Input value cannot include fraction or decimal");
} else if (bval === 0 || dval === 1) {
alert("Input value can only be 1s and 0s.");
} else {
convertByArray(dval);
}
//validity check, only 1s and 0s permitted, acknowledge spaces, cannot
//be negative
} else {
alert("Please select a conversion type.");
}
}
cT[1] (binary to decimal) is the section that's giving me trouble. When I run it in Firefox, it does return the input, just not the desired binary-to-decimal. Not sure what I'm doing wrong.
The dval variable has its own converter function, so figured declare a bval and give its own as follows, but still not the desired output. No idea what I'm doing wrong:
function convertByArray(dval) {
var rA = new Array();
var r,i,j;
i=0;
while (dval > 0) {
r = dval % 2; //remainder
rA[i] =r;
var nV = (dval - r) / 2;
$("txtCalc").value = $("txtCalc").value +
"Decimal " + dval + " divided by 2 = " + nV +
" w/ Remainder of: " + r +"\n";
i += 1;
dval = nV;
}
for(j=rA.length-1; j>=0; j--) {
$("txtOut").value = $("txtOut").value + rA[j];
}
}