Java Bit Operation on Long - Counting Set and Unset bits

前端 未结 3 538
庸人自扰
庸人自扰 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: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++;
    }
    

提交回复
热议问题