Java BitSet To Byte Array bitSetToByteArray(final BitSet bitSet, final int numBytes)

Here you can find the source of bitSetToByteArray(final BitSet bitSet, final int numBytes)

Description

This method makes up for a quirk in the standard java.util.BitSet class toByteArray() method, whereby high-end zero value bytes are discarded.

License

Open Source License

Parameter

Parameter Description
bitSet The input bitset whose underlying data should be returned a a byte array
numBytes The desired length in bytes of the byte array returned

Return

a byte array of the desired length

Declaration

public static byte[] bitSetToByteArray(final BitSet bitSet, final int numBytes) 

Method Source Code


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

import java.util.Arrays;
import java.util.BitSet;

public class Main {
    /**/*from w  w w  . j a  v  a 2  s  . c  o m*/
     * This method makes up for a quirk in the standard java.util.BitSet class toByteArray()
     * method, whereby high-end zero value bytes are discarded. This has the effect on returning
     * a byte array whose size is < the number of bits in the BitSet.
     * 
     * This method works around this by adding (or padding) with zeros where nessecary.
     * 
     * @param bitSet The input bitset whose underlying data should be returned a a byte array
     * @param numBytes The desired length in bytes of the byte array returned
     * @return a byte array of the desired length
     */
    public static byte[] bitSetToByteArray(final BitSet bitSet, final int numBytes) {
        return Arrays.copyOf(bitSet.toByteArray(), numBytes);
    }
}

Related

  1. bitsetToBinary(BitSet set, int n)
  2. bitSetToBinaryString(BitSet b, int startBit, int length)
  3. bitSetToBinaryString(BitSet strainBitSet)
  4. bitSetToByteArray(BitSet bitSet, int bitSetLength)
  5. bitSetToByteArray(BitSet bitSet, int byteLen)
  6. bitSetToBytes(BitSet bs)