Java BitSet to String bitsetToString(BitSet bs)

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

Description

bitset To String

License

Open Source License

Declaration

public static String bitsetToString(BitSet bs) 

Method Source Code

//package com.java2s;
/*//from  w  w  w. ja  v a  2s  . com
 * This file is part of MML.
 *
 *  MML 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.
 *
 *  MML 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 MML.  If not, see <http://www.gnu.org/licenses/>.
 *  (c) copyright Desmond Schmidt 2014
 */

import java.util.BitSet;

public class Main {
    public static String bitsetToString(BitSet bs) {
        StringBuilder sb = new StringBuilder();
        int start = 0;
        int old = 0;
        for (int v = bs.nextSetBit(0); v >= 0; v = bs.nextSetBit(v + 1)) {
            if (start == 0) {
                sb.append(v);
                old = v;
            } else if (v - start > 1) {
                if (old < start) {
                    sb.append("-");
                    sb.append(start);
                }
                sb.append(",");
                sb.append(v);
                old = v;
            }
            start = v;
        }
        if (start > old) {
            sb.append("-");
            sb.append(start);
        }
        return sb.toString();
    }
}

Related

  1. bitSet2String(BitSet b)
  2. bitSet2String(final BitSet bs)
  3. bitSetToString(BitSet bits, int length)
  4. bitsetToString(BitSet bitset, int width, int height)