Convert a BitSet to an unsigned BigInteger. - Java java.util

Java examples for java.util:BitSet

Description

Convert a BitSet to an unsigned BigInteger.

Demo Code


import java.math.BigInteger;
import java.util.BitSet;
import java.util.Map;

public class Main{
    /**//  w w w . java2 s  .  c  o m
     * Convert a BitSet to an unsigned BigInteger.
     * 
     * @param b BitSet to convert.
     * @param offset starting bit of the integer.
     * @param length number of bits to convert.
     * @return 
     */
    public static BigInteger bitSetToBigInt(BitSet b, int offset, int length) {
        return new BigInteger(BitSetUtils.toByteArray(b.get(offset, offset
                + length)));
    }
    /**
     * Convert a BitSet to an unsigned BigInteger.
     * @param b BitSet to convert.
     * @return 
     */
    public static BigInteger bitSetToBigInt(BitSet b) {
        return new BigInteger(BitSetUtils.toByteArray(b));
    }
    public static byte[] toByteArray(BitSet bits) {
        byte[] bytes = new byte[bits.length() / 8 + 1];
        for (int i = 0; i < bits.length(); i++) {
            if (bits.get(i)) {
                bytes[bytes.length - i / 8 - 1] |= 1 << (i % 8);
            }
        }
        return bytes;
    }
}

Related Tutorials