Vishwas
Vishwas

Reputation: 35

count 1s in a number's binary representation

I have figured out a way to calculate the number of set bits in a given number using a c program. Program as below:

    unsigned int countSetBits(unsigned int n) 
    { 
        unsigned int count = 0; 
        while (n)
        { 
            count += n & 1; 
            n >>= 1; 
        } 
        return count; 
     } 

Now i am trying implement the same in shell script, but facing the problem in one of the line

    count=0
    var=128

    while [ $var -gt 0 ]    
    do
            count=$(count + $((var&1))) // throws command not found on console
            var=$((var >> 1))
    done
    echo $count

Here, trying to print number of set bits in a variable var(128) ( expecting an output 1 bcz 128(10000000) has only one bit set.) Looking forward for your help as i am new to shell script.

Upvotes: 2

Views: 1055

Answers (1)

oguz ismail
oguz ismail

Reputation: 50750

count=$(count + $((var&1)))

You don't need to nest arithmetic expansions. And above line should look like:

count=$((count+(var&1)))

I'd write it this way though:

cnt=0 var=128
while [ "$var" -gt 0 ]; do
  : $((cnt+=var&1, var>>=1))
done
echo "$cnt"

Upvotes: 2

Related Questions