Bit

Counting set bits in Byte using Arrays

Pinterest LinkedIn Tumblr

Write a program to count the set bits in byte arrays.

source Code

package com.dsacode.Algorithm.bit;
 
public class NumberOfSetBits {
 
    public static int NoOfSetBits(int i)
    {
         i = i - ((i >> 1) & 0x55555555);
         i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
         return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
    }
     
    public static void main(String[] args) {
        System.out.println("Number of Set Bits of '12': "+ NoOfSetBits(12));
 
    }
 
}

Output

Number of Set Bits of '12': 2

Algorithm Explanation

Get the number.
Use Bits calculation to find the counting the set bits in byte arrays.

Reference

https://en.wikipedia.org/wiki/Bit_array

Write A Comment