0

How is it possible in Java to iterate over each bit in a byte? Lets assume to print each bit to the console seperately.

Olga
  • 1,516
  • 5
  • 17
  • 23

2 Answers2

3

You could do something like:

byte b;
for(int i = 1 ; i <= b ; i<<=1) int bit = b&i;
Maljam
  • 6,244
  • 3
  • 17
  • 30
-1

Turn your byte to a binary representation and go bit by bit:

final byte b1 = (byte) 129;
final String s1 = String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(' ', '0');
for (int i = 0; i < s1.length(); i++) {
    System.out.print(s1.charAt(i)); // 10000001
    if (s1.charAt(i) == '1') {
        System.out.println("= one");
    } else {
        System.out.println("= zero");
    }
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97