How to determine what is length of bits in bit set (zeros needs to be counted too)

```
uint16_t min = 1000000001;
uint16_t st1 = 10000000001;
uint16_t st2 = 100000000001;
uint16_t max = 1001000000001;
```

Every method i found it is counting only "1"

How to determine what is length of bits in bit set (zeros needs to be counted too)

```
uint16_t min = 1000000001;
uint16_t st1 = 10000000001;
uint16_t st2 = 100000000001;
uint16_t max = 1001000000001;
```

Every method i found it is counting only "1"

fireAngel:

Every method i found it is counting only "1"

All methods I know give 16.

```
sizeof(min)*8
```

First of all, none of those are binary numbers, so they won't fit in a uint16_t.

You probably meant:

```
uint16_t min = 0b1000000001;
```

Second, I'm not sure I understand what you mean.

Is bitSeqLen(0b10001) supposed to be 5?

What about bitSeqLen(0b101000)? 6, or 3?

Assuming the latter, you could do:

```
// Obscure and mysterious magic code!
#define bitSeqLen(x) ((sizeof(x)*8) - (__builtin_clz(x) + __builtin_ctz(x)))
```

(I think ... if this is homework, it would be very unwise to hand that in as a solution, unless you figure out and describe exactly how it works. But looking into it might offer some clues.)

fireAngel:

How to determine what is length of bits in bit set (zeros needs to be counted too)`uint16_t min = 1000000001;`

uint16_t st1 = 10000000001;

uint16_t st2 = 100000000001;

uint16_t max = 1001000000001;

`Every method i found it is counting only "1"`

sorry but could you clarify the above? the initialised values in your example are in binary right ie if converted to DEC that would be:

```
uint16_t min = 513; //1000000001
uint16_t st1 = 1025; //10000000001
uint16_t st2 = 2049; //100000000001
uint16_t max = 4609; //1001000000001
```

so tweaking @Whandall example to count 1's, I guess you can use this to find the "length of bits in bit set (zeros needs to be counted too)"

```
//using 'min' as example
uint16_t min = 513; //1000000001
uint8_t bit_cnt;
bit_cnt=0;
for (; min; min >>= 1) {
bit_cnt++;
}
Serial.print("min bit length:");
Serial.println(bit_cnt,DEC);
```

You can delete the leftmost bit in a twos-complement number like so:

```
int numbits = 0;
while(x) {
x = x & (x-1);
numbits++;
}
```

sherzaad:

`bit_cnt=0;`

for (; min; min >>= 1) {

bit_cnt++;

}

Works just fine ... thanks!!! (pumping Karma now)

just added an extra:

```
if (bit_cnt> 14)break;
```

to stop it if communication is broken (this is was needed for rev.eng. a communication protocol )

Given that the ‘length’ of variables is set along define boundaries, presumably you are looking for a means to determine how many msb are zero. So the position of the first non-zero bit determines the length?

Example 5 is 0b00000101 so the length would be 3?

If true,

```
byte x = (sizeof(c) * 8);
while(x)
{
if(c & (1 << (x-1))) break;
else x--;
}
```

will decrement the sizeof c until the first non-zero bit is located and will have the ‘length’ in x.