Monday, December 12, 2011

Need help converting binary to decimal through Javascript?

I need to devise a way for the script to display "Invalid binary number" whenever the input is not a valid 1's and 0's binary number, but I'm having trouble with it. This is what I have so far (didn't include variables)





for (i = 0; i %26lt; input.length; i++){





if(input.charAt(i) == '1' || input.charAt(i) == '0'){


document.BinaryForm.OutputText.value = ""


validinput = true;





}else if(input.charAt(i) != '1' %26amp;%26amp; input.charAt(i) != 0){


document.BinaryForm.OutputText.value = "Invalid binary number"


validinput = false;}





It disregards the first digit when I run the script, calculating the decimal value for the rest of it (for example, if I put in 50001, it comes up as two rather than the correct value of 1)





Any help is appreciated.|||just move your validinput initializer outside the loop, here's an abbreviated version:








validinput=true;


outputText="";


for(...)


{


if(good) { /* do nothing */ }


else { validinput = false ; outputText = "Invalid" ; }


}





This way, if there's 1 invalid bit, the flag stays as invalid rather than switching back on the next valid bit. I guess you could just throw a break in your original else case, too, but that's harder to follow.|||I limited you to 8-digits for the example, and I'm only showing the validation portion (limited search and destroy...exits for first illegal digit).





%26lt;html%26gt;


%26lt;head%26gt;


%26lt;script%26gt;


function chkBinaryInput(bin) {


var inVal = document.getElementById(bin).value;


var last = inVal.length;


if (last %26gt; 8) return false;


var isValid = true;


for (var i = 0; i %26lt; last; i++) {


isValid = isValid %26amp;%26amp;


-1 != '01'.indexOf(inVal.charAt(i));


if (!isValid) break;


}


return isValid;


}


%26lt;/script%26gt;


%26lt;/head%26gt;


%26lt;body%26gt;


%26lt;form%26gt;


Enter a binary numeral:


%26lt;input type="text" id="bin" /%26gt;



%26lt;input type="button"


value="click to validate"


onclick="alert(chkBinaryInput('bin'));鈥?/%26gt;


%26lt;/body%26gt;


%26lt;/html%26gt;

No comments:

Post a Comment