Returns a byte array of at least length 1
import java.util.BitSet; public class Main { public static void main(String[] argv) throws Exception { BitSet bitset = new BitSet(); bitset.set(1); System.out.println(toByteArray(bitset)); } 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; } }