Returns a newly constructed array containing the indices of the non-zero bits. - Java Language Basics

Java examples for Language Basics:Bit

Description

Returns a newly constructed array containing the indices of the non-zero bits.

Demo Code

/*******************************************************************************
 *   Copyright 2014 Analog Devices, Inc.
 *
 *   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./*from  ww w.  ja  v a  2  s . c  om*/
 ********************************************************************************/
//package com.java2s;
import java.util.BitSet;

public class Main {
    /**
     * Returns a newly constructed array containing the indices of the non-zero bits.
     * @since 0.07
     * @see #bitsetFromIndices
     */
    public static int[] bitsetToIndices(BitSet bits) {
        final int[] indices = new int[bits.cardinality()];
        for (int i = 0, index = -1, end = indices.length; i < end; ++i) {
            index = bits.nextSetBit(++index);
            indices[i] = index;
        }
        return indices;
    }
}

Related Tutorials