Java Bit Count countBits(int i)

Here you can find the source of countBits(int i)

Description

Count the number of non-zero bits of a integer

License

Apache License

Parameter

Parameter Description
i a parameter

Declaration

public static int countBits(int i) 

Method Source Code

//package com.java2s;
/*//from w w  w.  jav  a  2  s. c o  m
 * Copyright 2015 bladesilent@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

public class Main {
    /**
     * Count the number of non-zero bits of a integer
     * 
     * @param i
     * @return
     */
    public static int countBits(int i) {
        i = (((i & 0xAAAAAAAA) >>> 1) + (i & 0x55555555));
        i = (((i & 0xCCCCCCCC) >>> 2) + (i & 0x33333333));
        i = (((i & 0xF0F0F0F0) >>> 4) + (i & 0x0F0F0F0F));
        i = (((i & 0xFF00FF00) >>> 8) + (i & 0x00FF00FF));
        i = (((i & 0xFFFF0000) >>> 16) + (i & 0x0000FFFF));
        return i;
    }

    /**
     * Cont the number of non-zero bits of a short
     * 
     * @param i
     * @return
     */
    public static int countBits(short i) {
        i = (short) (((i & 0xAAAA) >>> 1) + (i & 0x5555));
        i = (short) (((i & 0xCCCC) >>> 2) + (i & 0x3333));
        i = (short) (((i & 0xF0F0) >>> 4) + (i & 0x0F0F));
        i = (short) (((i & 0xFF00) >>> 8) + (i & 0x00FF));
        return i;
    }
}

Related

  1. bitSizeForSignedValue(final int value)
  2. bitSizeForUnsignedValue(final int value)
  3. countBits (long v)
  4. countBits(byte num)
  5. countBits(final int intValue)
  6. countBits(int mask)
  7. countBits(int n)
  8. countBits(int x)
  9. countBits(int x)