convert long to BitSet bit by bit - Java java.util

Java examples for java.util:BitSet

Description

convert long to BitSet bit by bit

Demo Code


//package com.java2s;
import java.util.BitSet;

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

    public static BitSet convert(long value) {
        BitSet bits = new BitSet();
        int index = 0;
        while (value != 0L) {
            if (value % 2L != 0) {
                bits.set(index);
            }
            ++index;
            value = value >>> 1;
        }
        return bits;
    }

    public static long convert(BitSet bits) {
        long value = 0L;
        for (int i = 0; i < bits.length(); ++i) {
            value += bits.get(i) ? (1L << i) : 0L;
        }
        return value;
    }
}

Related Tutorials