Convert an integer to BitSet. - Java java.util

Java examples for java.util:BitSet

Description

Convert an integer to BitSet.

Demo Code


//package com.java2s;

import java.util.BitSet;

public class Main {
    public static void main(String[] argv) throws Exception {
        int value = 2;
        System.out.println(intToBitSet(value));
    }// www. ja v a  2s.c  om

    /**
     * Convert an integer to BitSet.
     * @param value Value to convert.
     * @return 
     */
    public static BitSet intToBitSet(int value) {
        BitSet bits = new BitSet();
        int index = 0;
        while (value != 0) {
            if (value % 2 != 0) {
                bits.set(index);
            }
            ++index;
            value = value >>> 1;
        }

        return bits;

    }

    /**
     * Stores an integer number in a BitSet object.
     *
     * @param value integer number to store
     * @param length number of bits to use.
     * @return
     */
    public static BitSet intToBitSet(int value, int length) {
        BitSet bits = new BitSet(length);
        int index = 0;
        while (value != 0) {
            if (value % 2 != 0) {
                bits.set(index);
            }
            ++index;
            value = value >>> 1;
        }

        return bits;
    }
}

Related Tutorials