Java Bit Count countBitsSet(int bitfield)

Here you can find the source of countBitsSet(int bitfield)

Description

count Bits Set

License

Open Source License

Declaration

public static int countBitsSet(int bitfield) 

Method Source Code

//package com.java2s;
/******************************************************************************
 * Copyright (c) 2004-2008 Whirlwind Match Limited. All rights reserved.
 *
 * This is open source software; you can use, redistribute and/or modify
 * it under the terms of the Open Software Licence v 3.0 as published by the 
 * Open Source Initiative./* ww w  .  j a v  a2s .  c  o m*/
 *
 * You should have received a copy of the Open Software Licence along with this
 * application. if not, contact the Open Source Initiative (www.opensource.org)
 *****************************************************************************/

public class Main {
    public static int countBitsSet(int bitfield) {
        int count = 0;
        for (short i = 0; i < Integer.SIZE; i++) {
            if ((bitfield & 0x01) != 0) {
                count++;
            }
            bitfield >>>= 1;
        }
        return count;
    }

    public static int countBitsSet(long bitfield) {
        int count = 0;
        for (short i = 0; i < Long.SIZE; i++) {
            if ((bitfield & 0x01) != 0) {
                count++;
            }
            bitfield >>>= 1;
        }
        return count;
    }
}

Related

  1. countBits(int x)
  2. countBits(long num)
  3. countBits(long value)
  4. countBitsInMask(int mask)
  5. countBitsNeeded(int value)