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:
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;
}
User contributions licensed under CC BY-SA 3.0