Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8032667
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T01:27:18+00:00 2026-06-05T01:27:18+00:00

I was looking into how Java counts bits set of an int. I had

  • 0

I was looking into how Java counts bits set of an int.
I had in my mind something simple like this (which I think is correct):

public static int bitCount(int number){  
        final int MASK = 0x1;  
        int count = 0;  

        for(int i = 0; i < 32; i++){  
            if(((number >>> i) & MASK) == MASK){  
                count++;  
            }  
        }  
        return count;  
    }  

Instead I found a method that I absolutely have no idea what is doing (seems like magic to me):

 i = i - ((i >>> 1) & 0x55555555);  
 i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);  
 i = (i + (i >>> 4)) & 0x0f0f0f0f;  
 i = i + (i >>> 8);  
 i = i + (i >>> 16);  
 return i & 0x3f;  

Could someone help understand what this does and why a simple function like the one I came up as first thought is/could be bad?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T01:27:19+00:00Added an answer on June 5, 2026 at 1:27 am

    Sure

    i = i - ((i >>> 1) & 0x55555555);
    

    The bit pattern of 5 is 0101 (four bits), so the mask is a repetition of the bit pattern 01 sixteen times. This line counts the number of bits in every two-bit pair of the number. If you consider two-bit pairs, (i >>> 1) & 0x1 gets the high-order bit in the low-order position. Now, there are four possible two-bit patterns

    00 ~> 00 - 00 = 00
    01 ~> 01 - 00 = 01
    10 ~> 10 - 01 = 01
    11 ~> 11 - 01 = 10
    

    and each two-bit pair now contains the number of bits the original had in those positions.

    i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
    

    Next, we count the bits that were in each four-bit group (aka nibble). By masking a nibble with 0x3 = 0011(b), we get the count of bits that were in the lower order two bits of the nibble, and (i >>> 2) & 0x3 gets the count from the higher order two bits of the nibble. These counts are now added. Since each count was at most 2, the sum is at most 4, hence doesn’t leave the nibble.

    i = (i + (i >>> 4)) & 0x0f0f0f0f;
    

    Now the bits in each octet are counted. Each nibble contains the count of bits set in the original in that place. Shifting right by four bits moves the count from the higher order nibble in each place to the lower order nibble, these are added. Then we also moved the count from the lower order nibble to the higher order nible of the adjacent octet, that is masked out by the & 0x0f0f0f0f. Since each octet can have at most eight bits set, the count doesn’t leave the lower order nibble of the octet.

    i = i + (i >>> 8);
    

    Now we add the counts of the pairs of adjacent octets.

    i = i + (i >>> 16);
    

    Now we add the totals of the counts in the high order two octets and the low order two.

    return i & 0x3f;
    

    Finally, all octets except the lowest order octet are masked out, since the higher order octets still contained intermediate counts.

    The reason why your simple implementation might be considered bad is performance. The convoluted bit-hack uses fewer operations and no branches, so it is faster. It is, however, far easier to get wrong.

    Another neat way to count the set bits in an int (or long) is

    public static int bitCount(int n) {
        int count = 0;
        while(n != 0) {
            ++count;
            n = n & (n-1);
        }
        return count;
    }
    

    That works because n = n & (n-1) clears the last set bit in n and leaves everything else untouched. If the bit pattern of n ends with

    ...100...0
    

    the bit pattern of n-1 is

    ...011...1
    

    and the bits before the last 1-bit in n are the same. In Java, that is guaranteed to work also for negative numbers because integer overflow has wrap-around semantics, so if n = Integer.MIN_VALUE, the bit pattern is 100...0 and n - 1 becomes Integer.MAX_VALUE with the bit pattern 011...1.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've been looking into JAX-RS lately because I really like the Java platform and
I'm looking into compressing binary data, more specifically serialized Java objects. I think I
I've been looking into Java reflections. This is an example from Wikipedia http://en.wikipedia.org/wiki/Reflection_(computer_programming ):
I'm looking into using this library for our Java-application: http://code.google.com/p/aparapi/ . One requirement for
I'm looking for a js library like StringUtils of commons-lang in java, which contains
I'm looking into some XSS prevention in my Java application. I currently have custom
We are looking into silent printing of PDF documents from within Java. The printing
I'm digging into Java EE for the first time in years. I'm looking for
I'm looking at integrating an ESB into an existing Java/Maven web based product. Specifically,
Looking into selector performance between $('#ID1, #ID2, #ID3') vs $('1X CLASS'). Which is faster?

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.