I want to manipulate a 32bit binary number in order to count the amount of "1". The input for my function is binary number like this 11111111111111111111111111111101. The problem is when this number is received from my function it generates a complete different binary string example ('10001100001111011110111110110001111011011011100110001000000000000000000000000000000000000000000000000000') or an exponential number. Both situations do not allow me to manipulate and work with a binary number imput.
Here is my code:
var countingOnes = function (n) {
let binx = { n: `${n.toString(2)}` };
console.log(binx);
let counter = 0;
for (let j = 0; j < binx.n.length; j++) {
if (binx.n.charAt(j) === "0") {
counter = counter;
} else {
counter = counter + 1;
}
}
console.log(counter);
};
countingOnes(11111111111111111111111111111101);
Many thanks in advance
I am not sure what your goal is but Bitwise operators may be what you are looking.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND_assignment
they allow you to perform bit manipulation to the actual numbers. Is there a specific reason why you need the output as a string?
have a look at this I have not fully tested it but seems to work assuming a 32bit integer...
function count1s(num = 5986) {
//parse to an integer
const integer = parseInt(num);
//loop through and count
let count = 0;
for(let i = 0; i < 32; i++) {
let test = integer >> (32 - i);
if((test % 2) === 1) {
count++;
}
}
//return the results
return count;
}
console.log(count1s());
after a few changes I have applied the following solution:
var countingOnes = function (n) {
let binx = n.toString(2);
let counter = 0;
for (let j = 0; j < binx.length; j++) {
if (binx.charAt(j) === "0") {
counter = counter;
} else {
counter = counter + 1;
}
}
return counter;
};
countingOnes("11111111111111111111111111111101");
Instead of considering the input as a number of 32 caracteres, I have considered the input as a string of 32 caracteres. Easier to manipulate. Thanks everyone for the contribution and suggestions!