Convert a BitSet to a string representation in base 10 assuming two's complement. - Java java.util

Java examples for java.util:BitSet

Description

Convert a BitSet to a string representation in base 10 assuming two's complement.

Demo Code


//package com.java2s;
import java.util.*;
import java.math.*;

public class Main {
    /**/* www.  j ava  2  s.co m*/
     * Convert a BitSet to a string representation in base 10 assuming two's complement.
     * 
     * @param bs The BitSet to convert.
     * @param bits The number of bits.
     * 
     * @return A string representation of the BitSet.
     */
    public static String ToStringSigned(BitSet bs, int bits) {

        // if bits = 0, can't do signed converstion
        if (bits == 0)
            return "unknown";

        // if positive do normal conversion
        if (!bs.get(bits - 1))
            return ToString(bs, 10);

        // flip the bits
        BitSet temp = (BitSet) bs.clone();
        temp.flip(0, bits);
        long val = ToLong(temp) + 1;
        return "-" + Long.toString(val);
    }

    /**
     * Convert a BitSet to a string representation in the specified radix.
     * 
     * @param bs The BitSet to convert.
     * @param radix The radix to convert the BitSet to.
     * 
     * @return A string representation of the BitSet in the specified radix.
     */
    public static String ToString(BitSet bs, int radix) {

        BigInteger bi = BigInteger.ZERO;

        for (int index = bs.nextSetBit(0); index >= 0; index = bs
                .nextSetBit(index + 1)) {
            bi = bi.setBit(index);
        }

        return bi.toString(radix).toUpperCase();
    }

    /**
     * Convert a bitset to a long.
     * 
     * @param bs The bitset.
     * 
     * @return the corresponding long.
     */
    public static long ToLong(BitSet bs) {

        long pow = 1;
        long value = 0;
        for (int i = 0; i < bs.length(); i += 1) {
            if (bs.get(i))
                value += pow;
            pow *= 2;
        }
        return value;
    }
}

Related Tutorials