Returns the value of the bit with the specified index. - Java Language Basics

Java examples for Language Basics:Bit

Description

Returns the value of the bit with the specified index.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int bitset = 2;
        int bitIndex = 2;
        System.out.println(get(bitset, bitIndex));
    }/*from w  w  w.ja v a  2s .  c o  m*/

    /** maximum index of a bitset (minimum index is 0) */
    public static final int MAX_INDEX = 31;

    /**
     * Returns the value of the bit with the specified index. The value is
     * <code>true</code> if the bit with the index <code>bitIndex</code> is
     * currently set in this <code>BitSet</code>; otherwise, the result is
     * <code>false</code>.
     * 
     * @param  bitset
     *         a bitset.
     * @param  bitIndex
     *         the bit index.
     * @return the value of the bit with the specified index.
     * @throws IndexOutOfBoundsException
     *         if the specified index is negative or greater than
     *         {@link #MAX_INDEX}
     */
    public static boolean get(int bitset, int bitIndex)
            throws IndexOutOfBoundsException {
        checkIndexRange(bitIndex, MAX_INDEX);
        return (bitset & (1 << bitIndex)) != 0;
    }

    /**
     * Throws an {@link IndexOutOfBoundsException} if the given bit index is
     * negative or if it the second argument is <code>true</code> also if the
     * index is greater than {@link #MAX_INDEX}.
     * 
     * @param  index
     * @param  checkMax
     * @throws IndexOutOfBoundsException
     */
    private static void checkIndexRange(int index, int maxIndex)
            throws IndexOutOfBoundsException {
        if (index < 0 || index > maxIndex)
            throw new IndexOutOfBoundsException("bitIndex [0..."
                    + MAX_INDEX + "]: " + index);
    }
}

Related Tutorials