Convert a byte or int to bitset

moesef picture moesef · Aug 5, 2012 · Viewed 20k times · Source

I have the following:

int num=Integer.parseInt(lineArray[0]);
byte numBit= num & 0xFF;

Is there any very simple way to convert numBit to a bit array? Or even better, is there a way to bypass the byte conversion of the int and go straigh from num to a bit array?

Thanks

Answer

obataku picture obataku · Aug 6, 2012

If you want a BitSet, try:

final byte b = ...;
final BitSet set = BitSet.valueOf(new byte[] { b });

If you want a boolean[],

static boolean[] bits(byte b) {
  int n = 8;
  final boolean[] set = new boolean[n];
  while (--n >= 0) {
    set[n] = (b & 0x80) != 0;
    b <<= 1;
  }
  return set;
}

or, equivalently,

static boolean[] bits(final byte b) {
  return new boolean[] {
    (b &    1) != 0,
    (b &    2) != 0,
    (b &    4) != 0,
    (b &    8) != 0,
    (b & 0x10) != 0,
    (b & 0x20) != 0,
    (b & 0x40) != 0,
    (b & 0x80) != 0
  };
}