Answer with a byte array representation of the supplied BitSet - Java java.util

Java examples for java.util:BitSet

Description

Answer with a byte array representation of the supplied BitSet

Demo Code


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

public class Main {
    /**/*from w  w  w.  java  2s.c  om*/
     * Answer with a byte array representation of the supplied BitSet
     * @param bitSet
     * @param length
     * @return
     * @throws IllegalArgumentException if the bitset is null
     */
    static byte[] bitset2bin(final BitSet bitSet, final int length) {
        if (bitSet == null) {
            throw new IllegalArgumentException("bitSet must be non-null");
        }

        final byte[] result = new byte[length];
        for (int bytenum = length - 1; bytenum >= 0; bytenum--) {
            result[bytenum] = 0;
            for (int bit = 0, mask = 0x80; mask >= 0x01; bit++, mask /= 2) {
                if (bitSet.get((bytenum * 8) + bit)) {
                    result[bytenum] |= mask;
                }
            }
        }
        return result;
    }
}

Related Tutorials