Java Bit Count countBitsInMask(int mask)

Here you can find the source of countBitsInMask(int mask)

Description

count Bits In Mask

License

Open Source License

Declaration

public static int countBitsInMask(int mask) 

Method Source Code

//package com.java2s;
/*//  w  w w.  j  a v  a 2 s .  c o m
 *    Qizx/open 4.1
 *
 * This code is the open-source version of Qizx.
 * Copyright (C) 2004-2009 Axyana Software -- All rights reserved.
 *
 * The contents of this file are subject to the Mozilla Public License 
 *  Version 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 *  for the specific language governing rights and limitations under the
 *  License.
 *
 * The Initial Developer of the Original Code is Xavier Franc - Axyana Software.
 *
 */

public class Main {
    public static int countBitsInMask(int mask) {
        switch (mask) {
        case -1:
            return 32;
        case 0:
            return 0;
        case 1:
        case 2:
        case 4:
        case 8:
            return 1;
        case 3:
        case 5:
        case 6:
            return 2;
        case 7:
            return 3;
        default:
            int count = 0;
            for (; mask != 0;) {
                if ((mask & 1) != 0)
                    ++count;
                mask >>>= 1;
            }
            return count;
        }
    }
}

Related

  1. countBits(int n)
  2. countBits(int x)
  3. countBits(int x)
  4. countBits(long num)
  5. countBits(long value)
  6. countBitsNeeded(int value)
  7. countBitsSet(int bitfield)