Java BitSet toByteArray(BitSet bits, int fixedNumBytes)

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

Description

Converts a BitSet into an array of bytes

License

Open Source License

Parameter

Parameter Description
bits a parameter

Declaration

public static byte[] toByteArray(BitSet bits, int fixedNumBytes) 

Method Source Code

//package com.java2s;
/*/*from  www .  j  a va  2 s . com*/
 *  $Author$
 *  $Date$
 *  $Revision$
 *
 *  Copyright (C) 2008-2009  Mark Rijnbeek
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2.1
 *  of the License, or (at your option) any later version.
 *  All we ask is that proper credit is given for our work, which includes
 *  - but is not limited to - adding the above copyright notice to the beginning
 *  of your source code files, and to any copyright notice that you may distribute
 *  with programs based on this work.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *
 */

import java.util.BitSet;

public class Main {
    /**
     * Converts a BitSet into an array of bytes
     * @param bits
     * @return
     */
    public static byte[] toByteArray(BitSet bits, int fixedNumBytes) {
        Double size = Math.ceil(new Double(fixedNumBytes) / 8);
        byte[] bytes = new byte[size.intValue()];

        for (int i = 0; i < fixedNumBytes; i++) {
            if (bits.get(i)) {
                bytes[bytes.length - i / 8 - 1] |= 1 << (i % 8);
            }
        }
        return bytes;
    }
}

Related

  1. toBitSet(final byte[] bytes)
  2. toBitSet(String data)
  3. toBitSet(String s, int length)
  4. toByteArray(BitSet bits)
  5. toByteArray(BitSet bits)
  6. toByteArray(BitSet bits, int sizeInBytes)
  7. toByteArray(BitSet bitSet)
  8. toByteArray(BitSet bs, int length)
  9. toFixedLengthByteArray(BitSet bs, int length)