Java BitSet toByteArray(BitSet bs, int length)

Here you can find the source of toByteArray(BitSet bs, int length)

Description

Convert a bit set into a byte array.

License

Open Source License

Parameter

Parameter Description
bs The bit set to be converted into byte array
length The number of bits used in the bit set

Return

The byte array derived from the bit set

Declaration

public static byte[] toByteArray(BitSet bs, int length) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.BitSet;

public class Main {
    /**/*from   w  w w  .ja v  a  2 s .c  om*/
     * Convert a bit set into a byte array. Note that the bit set may actually
     * be using non-integral number of bytes, but the conversion aligns it to
     * byte boundary.
     *
     * @param bs     The bit set to be converted into byte array
     * @param length The number of bits used in the bit set
     * @return The byte array derived from the bit set
     */
    public static byte[] toByteArray(BitSet bs, int length) {
        byte[] bytes = new byte[(int) Math.ceil((double) length / 8)];
        for (int i = 0; i < length; i++) {
            if (bs.get(i))
                bytes[i / 8] |= 1 << (7 - (i % 8));
        }
        return bytes;
    }
}

Related

  1. toByteArray(BitSet bits)
  2. toByteArray(BitSet bits)
  3. toByteArray(BitSet bits, int fixedNumBytes)
  4. toByteArray(BitSet bits, int sizeInBytes)
  5. toByteArray(BitSet bitSet)
  6. toFixedLengthByteArray(BitSet bs, int length)
  7. toggleInPlace(BitSet a, BitSet b)
  8. toInt(BitSet bitSet)
  9. toIntArray(final BitSet bits, final int size)