Sets the bit at the specified index to true. - Java Language Basics

Java examples for Language Basics:Bit

Description

Sets the bit at the specified index to true.

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(set(bitset, bitIndex));
    }//from www . j a  va  2  s.c o m

    /** maximum index of a bitset (minimum index is 0) */
    public static final int MAX_INDEX = 31;
    /** int with all bits set */
    public static final int INT_MASK = 0xffffffff;

    /**
     * Sets the bit at the specified index to <code>true</code>.
     * 
     * @param  bitset
     *         a bitset.
     * @param  bitIndex
     *         a bit index.
     * @return the bitset with the set bit.
     * @throws IndexOutOfBoundsException
     *         if the specified index is negative or greater than
     *         {@link #MAX_INDEX}
     */
    public static int set(int bitset, int bitIndex)
            throws IndexOutOfBoundsException {
        checkIndexRange(bitIndex, MAX_INDEX);
        return bitset | (1 << bitIndex);
    }

    /**
     * Sets the bits from the specified <tt>fromIndex</tt> (inclusive) to the
     * specified <tt>toIndex</tt> (exclusive) to <code>true</code>.
     * 
     * @param  bitset
     * @param  fromIndex
     *         index of the first bit to be set.
     * @param  toIndex
     *         index after the last bit to be set.
     * @return
     * @throws IndexOutOfBoundsException
     *         if <tt>fromIndex</tt> is negative,
     *         or <tt>toIndex</tt> is negative, or <tt>fromIndex</tt> is
     *         larger than <tt>toIndex</tt>.
     * @throws IllegalArgumentException
     */
    public static int set(int bitset, int fromIndex, int toIndex)
            throws IndexOutOfBoundsException, IllegalArgumentException {
        checkIndexRange(fromIndex, MAX_INDEX);
        checkIndexRange(toIndex, MAX_INDEX + 1);
        if (fromIndex > toIndex)
            throw new IllegalArgumentException(
                    "fromIndex parameter must be lower or equal to toIndex parameter");
        int mask = INT_MASK << fromIndex;
        mask &= INT_MASK >>> -toIndex;
        return bitset | mask;
    }

    /**
     * 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