23/02/2018

[Java] Count number of bits set to 1 in a byte type

Some more Java byte type related fun, how to count the number of bits set to 1 in a given byte.

 public int count(){  
  int tot = 0;  
   
  for(byte b = 0b00000001; b != 0b00000000; b = (byte)(b << 1)){  
   if((b & res) == b) tot++;  
  }  
   
  return tot;  
 }  


We can loop over it with some gotchas:
  • properly initialize our loop variable as byte value: 0bVALUE and set the rightmost bit to 1, using the same length as our byte variable we want to test
  • break the loop at 0b0, which is when we overflow with the shift
  • convert back to byte with a cast the result of << operation
  • check if the bit is set with a bitwise AND operation first

No comments:

Post a Comment

With great power comes great responsibility