Java Bit Operation on Long - Counting Set and Unset bits

前端 未结 3 550
庸人自扰
庸人自扰 2020-12-21 21:00

I have a long number. Now what I want is following (given in pseudo code) ,

int cnt1 = 0 
int cnt2 = 0 

for each two bits of that long

       if the two bi         


        
3条回答
  •  独厮守ぢ
    2020-12-21 21:20

    What you need to do is keep shifting by 2 bits to the right at every iteration and do a bitwise and (&) operation with the number 3 (11 in binary):

    long number;
    int cnt1 = 0;
    int cnt2 = 0;
    long test = 3;
    int counter = 0;    
    
    while(counter < 64) { // we have 64 bits to inspect
        if((number & test) == 3) { // last 2 bits are 11
            cnt1++;
        } else { // last 2 bits are either 10, 01 or 00
            cnt2++;
        }          
        counter += 2;
        number = number >>> 2; // shift by 2 bits to the right
    }
    

提交回复
热议问题