You said you want "convert binaries to decimal" (and unless it’s for learning purposes, I would use parseInt
, which although more direct, has some details to consider - detailed below).
Anyway, one way would be to actually check if the string has only zeros and ones, like one of the answers indicated.
Although, if the idea is to convert from binary to decimal, I would already do the validation during the conversion:
var result = document.querySelector('#result');
window.document.querySelector('input#b-input').addEventListener("input", function(e) {
var decimal = 0;
var s = e.target.value;
for (var i = 0; i < s.length; i++) {
var digito = parseInt(s[i]);
if (digito == 1) {
decimal += Math.pow(2, s.length - i - 1);
} else if (digito != 0) { // se for NaN também cai aqui
decimal = NaN;
break; // não é zero nem 1, posso interromper o loop
}
}
if (isNaN(decimal)) {
result.innerText = 'Não foi digitado um número binário';
} else {
result.innerText = `${s} em decimal=${decimal}`;
}
});
<form>
<input type="text" id="b-input">
</form>
<p id='result'></p>
That is, if during the conversion I find something that is not zero or one, it gives error. Otherwise, it continues to convert.
If you do the validation first and then the conversion also works, of course, but then you would have to go through the string twice, which seems unnecessary to me.
Another answer suggested using parseInt
, which is a more direct alternative (and as I have already said, is what I would recommend, unless your project is for learning purposes).
But there’s a detail, for parseInt
does not accept only zeros and ones, see:
for (var s of ['-01', ' 10', '10xyz'])
console.log(`${s} = ${parseInt(s, 2)}`);
Note that the character is also accepted -
(to indicate that the number is negative), and spaces at the beginning are ignored, as well as anything after the digits (so in the string 10xyz
, all after the x
is ignored). This behavior is described in documentation.
So, you have to decide what you want: only a string containing zeros and ones, or any string that can be converted from binary to decimal (according to Javascript rules, for example)? If you have spaces, will you ignore or fail? Etc...
It is worth remembering that negative numbers, as already seen above, must be represented with the minus sign in front. But there is also the possibility of representing such numbers using the complement of two (but then I believe I already escape a little of the scope of the question, but anyway it is something to consider, if I will implement the algorithm instead of using what already has ready).
You can use regular expression:
^[01]+$
.– Luiz Felipe
...I am creating an html project to convert binaries to decimal... why? Javascript has the function
parseInt(string, base)
parses a string argument and returns an integer in the specified base. Ex:console.log(parseInt("01001011",2));
returns75
.– Augusto Vasques
@Augustovasques, a learning project?
– Jefferson Quesado
@Jeffersonquesado, it may be.... has a good chance. I’m withdrawing the closing vote.
– Augusto Vasques