-1
\$\begingroup\$

I came up with a code in C++ that finds the position of all set bits in a binary representation of a number.I am using bitset class,however it seems the code ends up giving incorrect results when N>=10.

For example if N=11 then the output should be [0,2,3].

However in my case the output comes out to be 0,1 and 3.

Code is as follows:

#include <iostream>
#include<bitset>
using namespace std;

int main()
{
    
    int N=10;
    bitset<32> b(N);
    cout<<b.count()<<endl;
    for(int i=0;i<b.size();i++){
        if(b.test(i)){
            cout<<i<<endl;
        }
    }

    return 0;
}

So, I would like to know what is wrong with my current logic and also is there any other way to find the position of all bits set.

Input N output simply print the indexes where the bit is set in the binary representation of N.

New contributor
Sparsh Garg is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
5
  • \$\begingroup\$ 11 in binary is 1011, so bit 0, 1, and 3 are set. The output is correct. E: you can convince yourself by calculating 2^0 + 2^1 + 2^3 = 1 + 2 + 8 = 11 \$\endgroup\$
    – harold
    Nov 23 at 19:53
  • \$\begingroup\$ oh okay i was indexing from left to right 1(0),0(1).1(2) and 1(3), \$\endgroup\$ Nov 23 at 19:59
  • \$\begingroup\$ Then wouldn't you expect 28, 30, 31? Since you're using a bitset<32>, if we started to count at the top, there would first be 28 zeroes before the 1011 \$\endgroup\$
    – harold
    Nov 23 at 20:04
  • \$\begingroup\$ If you were counting wrong, wouldn't you also notice a difference from you expectations on inputs of 2,4,6... well, just about every number except 1, 3, 5, and 7? \$\endgroup\$
    – JDługosz
    Nov 23 at 20:16
  • \$\begingroup\$ JDlugosz,you are right I noticed that issue ,but i needed some clarifications ,that is why i posted this question on the stackexchange \$\endgroup\$ Nov 24 at 10:26

Browse other questions tagged or ask your own question.