Convert a bitset into displayable values (hex,unsigned,signed). - Java java.util

Java examples for java.util:BitSet

Description

Convert a bitset into displayable values (hex,unsigned,signed).

Demo Code


import java.util.*;
import java.math.*;

public class Main{
    /**//from   ww w. ja  va  2 s. c o  m
     * Convert a bitset into displayable values (hex,unsigned,signed).
     * A null bitset is converted to "HiZ".
     * 
     * @param value The BitSet.
     * @param bits The number of bits in the value.
     * 
     * @return A string in the form "0xn (n unsigned, n signed)" or "HiZ".
     */
    public static String toDisplay(BitSet value, int bits) {

        if (value == null)
            return "HiZ";
        String str = "0x" + BitSetUtils.ToString(value, 16);
        str += " (" + BitSetUtils.ToString(value, 10) + " unsigned, ";
        str += BitSetUtils.ToStringSigned(value, bits) + " signed)";
        return str;
    }
    /**
     * 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 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 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