Sanjay Jain - 10 months ago 60

C++ Question

How to iterate through a binary number in c++?

In the mentioned function I'm getting

invalid operands to binary conversion (bitset<8> and int)

This is the function in my code, which is getting the stated error

`int value(int x)`

{

int temp=0,counter=0;

bitset<8> i(x);

while (i != 0) {

temp = i % 10;

if(temp == 1) {

counter++;

}

i = i/10;

}

return counter;

}

Answer Source

To count the number of 1's in the first 8 bits of x:

```
int value(int x)
{
return bitset<8>(x).count();
}
```

To count all the bits:

```
int value(int x)
{
return bitset<sizeof(x) * CHAR_BIT>(x).count();
}
```

If you have to use a loop solution: (Adaption to your solution with available functions)

```
int value(int x)
{
int counter=0;
bitset<8> i(x);
while (i != 0) {
if(i[0] == 1) {
counter++;
}
i >>= 1;
}
return counter;
}
```