How to convert a byte into bits?

If you just need the String representation of it in binary you can simply use Integer.toString() with the optional second parameter set to 2 for binary.

To perform general bit twiddling on any integral type, you have to use logical and bitshift operators.

// tests if bit is set in value
boolean isSet(byte value, int bit){
   return (value&(1<<bit))!=0;
} 

// returns a byte with the required bit set
byte set(byte value, int bit){
   return value|(1<<bit);
}

You might find something along the lines of what you're looking in the Guava Primitives package.

Alternatively, you might want to write something like

public boolean[] convert(byte...bs) {
 boolean[] result = new boolean[Byte.SIZE*bs.length];
 int offset = 0;
 for (byte b : bs) {
  for (int i=0; i<Byte.SIZE; i++) result[i+offset] = (b >> i & 0x1) != 0x0;
  offset+=Byte.SIZE;
 }
 return result;
}

That's not tested, but the idea is there. There are also easy modifications to the loops/assignment to return an array of something else (say, int or long).


BitSet.valueOf(byte[] bytes)

You may have to take a look at the source code how it's implemented if you are not using java 7

Tags:

Java