Java Bit Count bitCountSlow(int x)

Here you can find the source of bitCountSlow(int x)

Description

Count the number of set bits in an int;

License

Open Source License

Parameter

Parameter Description
x the int to have its bits counted

Declaration

static int bitCountSlow(int x) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /** Count the number of set bits in an int;
     *  @param x the int to have its bits counted
     *  @author Tim Tyler tt@iname.com// w  w  w. ja va  2s . c  o m
     *  @returns the number of bits set in x
     */
    static int bitCountSlow(int x) {
        int temp;

        temp = 0x55555555;
        x = (x & temp) + (x >>> 1 & temp);
        temp = 0x33333333;
        x = (x & temp) + (x >>> 2 & temp);
        temp = 0x07070707;
        x = (x & temp) + (x >>> 4 & temp);
        temp = 0x000F000F;
        x = (x & temp) + (x >>> 8 & temp);

        return (x & 0x1F) + (x >>> 16);
    }

    /** Count the number of set bits in an long;
     *  @param x the long to have its bits counted
     *  @author Tim Tyler tt@iname.com
     *  @returns the number of bits set in x
     */
    static int bitCountSlow(long x) {
        long temp;

        temp = 0x5555555555555555L;
        x = (x & temp) + (x >>> 1 & temp);
        temp = 0x3333333333333333L;
        x = (x & temp) + (x >>> 2 & temp);
        temp = 0x0707070707070707L;
        x = (x & temp) + (x >>> 4 & temp);
        temp = 0x000F000F000F000FL;
        x = (x & temp) + (x >>> 8 & temp);
        temp = 0x0000001F0000001FL;
        x = (x & temp) + (x >>> 16 & temp);

        return (int) ((x & 0x3f) + (x >>> 32));
    }
}

Related

  1. bitCount(final Integer i)
  2. bitCount(int i)
  3. bitcount(int num)
  4. bitCount(int x)
  5. bitCount(String s)
  6. bitLength(byte[] bytes)
  7. bitLength(final int byteLength)
  8. bitLength(int num)
  9. bitLength(int value)