Violet Giraffe
Violet Giraffe

Reputation: 33589

Simplest to break a byte down to 8 bits?

I have a byte and want to get a collection of 8 bits (represented as 0 or 1 in any built-in integer type - boolean, int, char). Is there any built-in way to do this?

Upvotes: 1

Views: 199

Answers (3)

paul
paul

Reputation: 13516

How about a function?

public static int getBit(byte b, int bit)
{
    int power = 1 << bit;
    return (b & power) ? 1 : 0;
}

public static void main(String[] args)
{
    for (int j = 0; j < 8; j++)
    {
        System.out.println(getBit(0x55, j));
    }
}

Upvotes: 2

Danstahr
Danstahr

Reputation: 4319

You might be interested in BitSet and its methods BitSet.valueOf() and BitSet.get() .

Upvotes: 3

Pphoenix
Pphoenix

Reputation: 1473

A really simple way would be to convert the byte to an integer, and then use the built in functions to convert to binary. Since the byte data type is an 8-bit signed two's complement integer, you can actually use it like this:

byte b = (byte)53;
String binary = Integer.toString((int)b, 2); // convert to base 2

Upvotes: 0

Related Questions