Java Utililty Methods BitSet To Byte Array

List of utility methods to do BitSet To Byte Array

Description

The list of methods to do BitSet To Byte Array are organized into topic(s).

Method

StringbitsetToBinary(BitSet set, int n)
bitset To Binary
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++)
    sb.append(set.get(i) ? "1" : "0");
return sb.toString();
StringbitSetToBinaryString(BitSet b, int startBit, int length)
Convert a BitSet to a binary representation string.
return bitSetToBinaryString(b, startBit, length, 4);
StringbitSetToBinaryString(BitSet strainBitSet)
Convert the bit set to its string representation
StringBuffer sb = new StringBuffer(strainBitSet.length());
for (int i = 0; i < strainBitSet.length(); i++) {
    sb.append(strainBitSet.get(i) ? '1' : '0');
return sb.toString();
byte[]bitSetToByteArray(BitSet bitSet, int bitSetLength)
bit Set To Byte Array
byte[] ret = bitSet.toByteArray();
if (ret.length == bitSetLength) {
    return ret;
byte[] finalRet = new byte[bitSetLength % 8 == 0 ? bitSetLength / 8 : bitSetLength / 8 + 1];
System.arraycopy(ret, 0, finalRet, 0, ret.length);
return finalRet;
byte[]bitSetToByteArray(BitSet bitSet, int byteLen)
bit Set To Byte Array
byte[] result = new byte[byteLen];
for (int i = 0; i < byteLen; i++) {
    for (int j = 7; j >= 0; j--) {
        if (bitSet.length() < (i * 8 + (7 - j)))
            return result;
        if (bitSet.get(i * 8 + (7 - j)))
            result[i] |= (0x01 << j);
return result;
byte[]bitSetToByteArray(final BitSet bitSet, final int numBytes)
This method makes up for a quirk in the standard java.util.BitSet class toByteArray() method, whereby high-end zero value bytes are discarded.
return Arrays.copyOf(bitSet.toByteArray(), numBytes);
byte[]bitSetToBytes(BitSet bs)
Copy a BitSet to a byte array
byte[] bytes = new byte[bs.size() / 8];
for (int i = 0; i < bytes.length; ++i) {
    for (int j = 0; j < 8; ++j) {
        if (bs.get(i * 8 + j))
            bytes[i] |= 1 << j;
return bytes;
...