Reputation: 1
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];
}
}
Upvotes: 0
Views: 92
Reputation: 44086
Can't really follow all of that. If you are looking just to convert bin to dec, all it takes is one method parseInt(num, radix)
.
This demo can convert decimal, binary, and hexadecimal
const convert = (rxFrom, rxTo, number) => parseInt(number, rxFrom).toString(rxTo);
let bin1 = 1101001;
let bin2 = 10100001;
let dec1 = 5641;
let dec2 = 97;
let hex1 = `ff96ca`;
let hex2 = `25dc5b`;
const bin2dec = convert(2, 10, bin1);
const bin2hex = convert(2, 16, bin2);
const dec2bin = convert(10, 2, dec1);
const dec2hex = convert(10, 16, dec2);
const hex2dec = convert(16, 10, hex1);
const hex2bin = convert(16, 2, hex2);
console.log(bin2dec);
console.log(bin2hex);
console.log(dec2bin);
console.log(dec2hex);
console.log(hex2dec);
console.log(hex2bin);
Upvotes: 1