What does this piece of code does?

int count(int k){
    int dem = 0;
    for(int i=0;i<10;i++){
        if (k & 1 << i)
            dem++;
    }
    return dem;
}

Can anyone help me with function what it does basically?

2 Likes

It counts how many of the first 10 bits of k are set.

2 Likes

but where it is used?

It count the number of set bits(i.e. 1) in k in last 10 bits (starting from LSB toward MSB).

1 Like

It is used where one has work on binary level i.e. Bit Manipulation/Masking.
A very basic use can be to convert integers to binary and it is faster than the trivial method of division by 2. Obtained binary can be stored in String or Bitset(in C++ STL).

2 Likes