Convert an 8 bit int (unsigned byte) to a bitset - Java java.util

Java examples for java.util:BitSet

Description

Convert an 8 bit int (unsigned byte) to a bitset

Demo Code


import java.util.BitSet;

public class Main{
    /**/*w ww  .  j  a  va 2  s. c  o m*/
     * Convert an 8 bit int (unsigned byte) to a bitset
     * @param byteValue The 8bit int value
     * @return bitset for the byte
     */
    public static BitSet byte8ToBitSet(int byteValue) {
        return valueToBitSet(byteValue, 8);
    }
    /**
     * Convert a value to a bitset
     * @param byteValue The value to convert
     * @param size How many bits are in the value (ex: 8 for bit, 32 for int)
     * @return The bitset for the value
     */
    public static BitSet valueToBitSet(int byteValue, int size) {
        // create a bit set to hold values
        BitSet returnBitSet = new BitSet(size);
        //byte shiftedValue = byteValue;
        int shiftedValue = byteValue;
        if (byteValue < 0) {
            if (size == Byte.SIZE)
                shiftedValue = DataUtil.signedToUnsigned((byte) byteValue);
            if (size == Integer.SIZE)
                shiftedValue = DataUtil.signedToUnsigned(byteValue);
        }

        // loop through the size which should be either a 8 for a byte or 32 for an int
        for (int i = (size - 1); i >= 0; i--) {
            boolean setVal = ((shiftedValue >> i) == 1);
            returnBitSet.set(i, setVal);

            if (setVal)
                shiftedValue ^= (1 << i);
        }
        return returnBitSet;
    }
    /**
     * Signed byte to an unsigned value
     * @param byteValue The byte value
     * @return an int with value of byteValue unsigned
     */
    public static int signedToUnsigned(byte byteValue) {
        return byteValue & 0xFF;
    }
    /**
     * Signed into to unsigned
     * @param intValue The int value to convert
     * @return an unsigned int
     */
    public static int signedToUnsigned(int intValue) {
        return intValue & 0xFFFFFFFF;
    }
}

Related Tutorials