Here you can find the source of bitsToBytes(BitSet ba, int size)
public static byte[] bitsToBytes(BitSet ba, int size)
//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); } }