Java BitSet to bitsToBytes(BitSet ba, int size)

Here you can find the source of bitsToBytes(BitSet ba, int size)

Description

Pack the bits in ba into a byte[].

License

Open Source License

Declaration

public static byte[] bitsToBytes(BitSet ba, int size) 

Method Source Code

//package com.java2s;
/*//w  w  w  .j  a va 2  s.  c om
 *   This file is part of dhcp4java, a DHCP API for the Java language.
 *   (c) 2006 Stephan Hadinger
 *
 *   This library is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU Lesser General Public
 *   License as published by the Free Software Foundation; either
 *   version 2.1 of the License, or (at your option) any later version.
 *
 *   This library is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *   Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public
 *   License along with this library; if not, write to the Free Software
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

import java.util.BitSet;

public class Main {
    /**
     * Pack the bits in ba into a byte[].
     */
    public static byte[] bitsToBytes(BitSet ba, int size) {
        int bytesAlloc = countBytesForBits(size);
        byte[] b = new byte[bytesAlloc];

        for (int i = 0; i < b.length; i++) {
            short s = 0;

            for (int j = 0; j < 8; j++) {
                int idx = i * 8 + j;
                boolean val = (idx <= size && ba.get(idx));

                s |= (val ? (1 << j) : 0);
            }

            if (s > 255) {
                throw new IllegalStateException("WTF? s = " + s);
            }

            b[i] = (byte) s;
        }
        return b;
    }

    /**
     *  <at> return the number of bytes required to represent the
     * bitset
     */
    public static int countBytesForBits(int size) {
        // Brackets matter here! == takes precedence over the rest
        return (size / 8) + ((size % 8) == 0 ? 0 : 1);
    }
}

Related

  1. bitsetToIndices(BitSet bits)
  2. bitSetToInt(final BitSet bitSet)
  3. bitSetToLong(BitSet set)
  4. bitSetToMap(Map map, String key, BitSet bits, int length)
  5. bitSetToUnsignedInt(BitSet b, int startBit, int length)
  6. BitsToBytes(BitSet bits)
  7. bitsToHexString(BitSet ba, int size)
  8. BitsToInt(BitSet bits, int length)
  9. convert(BitSet bits)