Java Bit Operation on Long - Counting Set and Unset bits

前端 未结 3 539
庸人自扰
庸人自扰 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:06

    A short answer.

    long num = ~0L;
    int cnt1 = Long.bitCount(num & (num >>> 1) & 0x5555555555555555L);
    System.out.println(cnt1);
    int cnt2 = 32 - cnt1;
    

    prints

    32
    
    0 讨论(0)
  • 2020-12-21 21:16

    What you need to do is create a bit-mask and run it over your value, assuming this is homework I will only give some pointers:

    • the bit-mask you already gave: long mask = 0x03L;
    • to check every other 2 bits, shift your mask left 2 potisions
    • you can use a for-loop to check the value until your mask has value 0
    • use the bitwise-and operator & to check a value against a mask

    If you put above hints into code, you will have your answer :-)

    Edit now that the results are in, my solution would be:

    long cnt1 = 0;
    long cnt2 = 0;
    
    for (long mask = 0x03; mask != 0; mask <<=2) {
    
        (mask == (value & mask)) ? cnt1++ : cnt2++;
    }
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
提交回复
热议问题