Java BitSet to Bitset2BitString(BitSet bitset, int length)

Here you can find the source of Bitset2BitString(BitSet bitset, int length)

Description

Converts the given BitSet to a {0,1}-String of the given length.

License

Open Source License

Parameter

Parameter Description
bitset the BitSet to convert
length the length of the resulting String

Exception

Parameter Description
IllegalArgumentException if BitSet#size() smaller than the given length

Return

{0,1}-String representation of bitset

Declaration

public static String Bitset2BitString(BitSet bitset, int length) 

Method Source Code


//package com.java2s;
/*// w w w  . j av  a  2 s  . co m
 * Scaffold Hunter
 * Copyright (C) 2006-2008 PG504
 * Copyright (C) 2010-2011 PG552
 * See the file README.txt in the root directory of the Scaffold Hunter
 * source tree for details.
 *
 * Scaffold Hunter 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 3 of the License, or
 * (at your option) any later version.
 *
 * Scaffold Hunter 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, see <http://www.gnu.org/licenses/>.
 */

import java.util.BitSet;

public class Main {
    /**
     * Converts the given {@link BitSet} to a {0,1}-String of the given length.
     * 
     * @param bitset
     *            the {@link BitSet} to convert
     * @param length
     *            the length of the resulting String
     * @return {0,1}-String representation of bitset
     * @throws IllegalArgumentException
     *             if {@link BitSet#size()} smaller than the given length
     */
    public static String Bitset2BitString(BitSet bitset, int length) {
        if (bitset.size() < length) {
            throw new IllegalArgumentException("length if longer than the bitset lenght");
        }

        StringBuilder builder = new StringBuilder(length);

        for (int i = length - 1; i >= 0; i--) {
            if (bitset.get(i)) {
                builder.append("1");
            } else {
                builder.append("0");
            }
        }
        return builder.toString();
    }
}

Related

  1. bitSet2byte(BitSet b, int bytes)
  2. bitset2bytes(BitSet bits, byte[] bytes)
  3. bitSet2extendedByte(BitSet b)
  4. bitSet2Int(BitSet bs)