Java BitSet To Byte Array bitSetToBytes(BitSet bs)

Here you can find the source of bitSetToBytes(BitSet bs)

Description

Copy a BitSet to a byte array

License

Open Source License

Parameter

Parameter Description
bs a parameter

Declaration

public static byte[] bitSetToBytes(BitSet bs) 

Method Source Code

//package com.java2s;
/* Image to ZX Spec// w  ww  .  j av  a  2s. c  o m
 * Copyright (C) 2014 Silent Software (Benjamin Brown)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

import java.util.BitSet;

public class Main {
    /**
     * Copy a BitSet to a byte array
     * @param bs
     * @return
     */
    public static byte[] bitSetToBytes(BitSet bs) {
        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;
    }
}

Related

  1. bitSetToBinaryString(BitSet b, int startBit, int length)
  2. bitSetToBinaryString(BitSet strainBitSet)
  3. bitSetToByteArray(BitSet bitSet, int bitSetLength)
  4. bitSetToByteArray(BitSet bitSet, int byteLen)
  5. bitSetToByteArray(final BitSet bitSet, final int numBytes)