# Counting 1's and 0's in a bit sequence

1

These two methods are from Hacker's Delight. I wish to count the number of 0's and 1's in a bit sequence.

For example, for the following sequence `00000000000000000011011100111101` , I thought after removing the leading zeros I would get:

• 2 Ones
• 1 Zero
• 3 Ones
• 2 Zero
• 4 Ones
• 1 Zero
• 1 One

I though this result is obtained by subtracting the the p values that store the counted zeros and ones.

But I don't get these values exactly from the ffstrl method. What am I missing ?

``````private  void ffstrl(int x){
int k,p;
p = 0;
while(x != 0){
k = nlz(x); //Count zeros
x = x << k ;
p = p + k;
k = nlz(~x); //Count Ones

x = x << k;
p = p + k;
}
}

int nlz(int x){
if( x == 0){
return 32;
}
int n = 0;
if( x <= 0x0000FFFF) { n =  n + 16; x = x << 16;}
if( x <= 0x00FFFFFF) { n =  n + 8; x = x << 8;}
if( x <= 0x0FFFFFFF) { n =  n + 4; x = x << 4;}
if( x <= 0x3FFFFFFF) { n =  n + 2; x = x << 2;}
if( x <= 0x7FFFFFFF) { n =  n + 1;}
return n;
}
``````
java
bit
asked on Stack Overflow Aug 29, 2014 by Mohan Radhakrishnan • edited Oct 30, 2019 by Mohan Radhakrishnan