Java Convert via ByteBuffer toByteArray(BitSet bits)

Here you can find the source of toByteArray(BitSet bits)

Description

Convert BitSet to byte array

License

Open Source License

Parameter

Parameter Description
bits Array of bits

Return

Array of bytes

Declaration

public static byte[] toByteArray(BitSet bits) 

Method Source Code

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

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.*;

public class Main {
    /**//from   w  w w.j av  a2s  . c  o m
     * Convert short array to byte array
     * @param arr Array of shorts
     * @return Array of bytes
     */
    public static byte[] toByteArray(short[] arr) {
        byte[] byteBlocks = new byte[arr.length * 2];
        ByteBuffer.wrap(byteBlocks).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(arr);
        return byteBlocks;
    }

    /**
     * Convert BitSet to byte array
     * @param bits Array of bits
     * @return Array of bytes
     */
    public static byte[] toByteArray(BitSet bits) {
        byte[] result = new byte[(bits.length() + 7) / 8];
        for (int i = 0; i < bits.length(); ++i) {
            if (bits.get(i)) {
                result[i / 8] |= 1 << (i % 8);
            }
        }
        return result;
    }
}

Related

  1. toBuffer(Serializable obj)
  2. toBuffer(String spacedHex)
  3. toByte(char data)
  4. toByte(final char[] charArray)
  5. toByte(int input, int count)
  6. toByteArray(char[] chars)
  7. toByteArray(double value)
  8. toByteArray(double[] doubleArray)
  9. toByteArray(float[] floatArray)