Java BitSet toFixedLengthByteArray(BitSet bs, int length)

Here you can find the source of toFixedLengthByteArray(BitSet bs, int length)

Description

Converts a BitSet to a byte[] including length bytes (length*8 bits).

License

Open Source License

Parameter

Parameter Description
bs BitSet, to convert to a byte array
length int, length of generated array

Return

byte[] of length

Declaration

public static byte[] toFixedLengthByteArray(BitSet bs, int length) 

Method Source Code


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

import java.util.BitSet;

public class Main {
    /**//from  www  .java 2s. c o  m
     * Converts a BitSet to a byte[] including length bytes (length*8 bits). 
     * May temporarily create a BitSet to force sufficient length.
     * @param bs BitSet, to convert to a byte array
     * @param length int, length of generated array
     * @return byte[] of length 
     */
    public static byte[] toFixedLengthByteArray(BitSet bs, int length) {
        BitSet prefix = bs.get(0, length * 8);
        BitSet lastByte = prefix.get((length - 1) * 8, length * 8);
        if (lastByte.cardinality() > 0) { // happy path, last bit set
            return prefix.toByteArray();
        } else { // last bit zero, need to fiddle
            prefix.set(length * 8 - 1);
            byte[] a = prefix.toByteArray();
            a[a.length - 1] = 0;
            return a;
        }
    }
}

Related

  1. toByteArray(BitSet bits)
  2. toByteArray(BitSet bits, int fixedNumBytes)
  3. toByteArray(BitSet bits, int sizeInBytes)
  4. toByteArray(BitSet bitSet)
  5. toByteArray(BitSet bs, int length)
  6. toggleInPlace(BitSet a, BitSet b)
  7. toInt(BitSet bitSet)
  8. toIntArray(final BitSet bits, final int size)
  9. toInteger(final BitSet bits)