user3595099 user3595099 - 19 days ago 8
HTML Question

Counting number of 1 bits in binary representation

I tried with the below code to convert decimal input into its binary representation, and then to count the number of 1's in it

When I run the below code, there is no output and there are no errors reported:

function demo() {
var arra, i, rem;
var Input = document.getElementById('demo');
arra = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var x = 1;
while (Input > 0) {
rem = Input % 2;
Input = (parseInt(Input / 2));
if (rem > 0) {
arra[i] = 1;
i = i + 1;
} else {
i = i + 1;
}
}

while (x < 35) {
if (arra[x] == 1) {
document.getElementById("output").innerHTML = "SOB Found";
x = x + 1;
} else {
x = x + 1;
}
}
}


HTML Code:

<!doctype html>
<html>
<head>
<title>Test Phase</title>
<script src="SOB.js" type="text/javascript"></script>
</head>
<body>
<input type="text" name="value" id="Input" />
<input type="submit" value="submit" onClick="demo()" />
<p id="output"> </p>
<script src="SOB.js" type="text/javascript"></script>
</body>
</html>

Answer

There are several issues, but you can do this with much less code by using the .toString(2) method:

function demo() {
    // Get input value via value property and convert to number (+)
    var val = +document.getElementById("input").value;
    // Convert to binary representation:
    var bin = val.toString(2);
    // Count the number of 1 bits, by counting the number of 
    //    matches when looking for 1s:
    var ones = bin.match(/1/g).length;
    // Output results, using textContent, not innerHTML:
    document.getElementById("binary").textContent = bin;
    document.getElementById("ones").textContent = ones;
}
<input type="text" name="value" id="input">
<input type="submit"  value="submit" onclick="demo()">
<p>
Binary: <span id="binary"></span><br>
One bits: <span id="ones"></span>
</p>

Comments