Here you can find the source of countBits(final int intValue)
Parameter | Description |
---|---|
intValue | int value. |
public static int countBits(final int intValue)
//package com.java2s; /*/* w ww .j a v a2s. c om*/ * Copyright 2013, Carsten J?ger * * 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 { /** * Constant 4. */ public static final byte CONST_4 = 4; /** * Constant 8. */ public static final byte CONST_8 = 8; /** * Counts the number of 1-Bits in a 32-bit int value and uses a "divide-and-conquer" strategy. (see Hacker's * Delight, Section 5.1). * * @param intValue int value. * @return Number of 1-Bits. */ public static int countBits(final int intValue) { final byte const16 = 16; final byte const3F = 0x0000003F; final int const33 = 0x33333333; final int const55 = 0x55555555; final int const0F = 0x0F0F0F0F; int result = intValue; result -= ((result >>> 1) & const55); result = (result & const33) + ((result >>> 2) & const33); result = (result + (result >>> CONST_4)) & const0F; result += (result >>> CONST_8); result += (result >>> const16); return result & const3F; } }