Create a bitset from a positive long. - Java java.util

Java examples for java.util:BitSet

Description

Create a bitset from a positive long.

Demo Code


//package com.java2s;
import java.util.*;
import java.math.*;

public class Main {
    public static void main(String[] argv) throws Exception {
        long value = 2;
        System.out.println(Create(value));
    }/*from   ww  w.  j ava 2s  . c o  m*/

    /**
     * Create a bitset from a positive long.
     * 
     * @param value The long value.
     * 
     * @return The corresponding BitSet.
     * 
     * @throws IllegalArgumentException if value is negative
     */
    public static BitSet Create(long value) {

        if (value < 0)
            throw new IllegalArgumentException(
                    "value must be greater than zero (" + value + ")");
        BitSet newBS = new BitSet();
        int highBit = (int) Math.ceil(Math.log(value + 1) / Math.log(2));
        for (int index = 0; index < highBit; index += 1) {
            long bit = (long) Math.pow(2, index);
            newBS.set(index, (bit & value) == bit);
        }
        return newBS;
    }

    /**
     * Create a bitset from a positive BigInteger.
     * 
     * @param value The BigInteger value.
     * 
     * @return The corresponding BitSet.
     * 
     * @throws IllegalArgumentException if value is negative
     */
    public static BitSet Create(BigInteger value) {

        if (value.compareTo(BigInteger.ZERO) < 0)
            throw new IllegalArgumentException(
                    "value must be greater than zero (" + value + ")");
        int numbits = value.bitLength() + 1;
        BitSet newBS = new BitSet(numbits);
        for (int index = 0; index < numbits; index += 1) {
            if (value.testBit(index)) {
                newBS.set(index);
            }
        }
        return newBS;
    }
}

Related Tutorials