Java examples for java.util:BitSet
Convert byte to bitset
import java.util.BitSet; public class Main{ /**//w w w .ja v a 2s . c o m * Convert byte to bitset * @param byteValue byte value to convert * @return bitset for the byte */ public static BitSet byteToBitSet(byte 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; } }