Java Iterate Bits in Byte Array

前端 未结 7 1556
夕颜
夕颜 2020-12-08 02:49

How can i iterate bits in a byte array?

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 03:16

    I know, probably not the "coolest" way to do it, but you can extract each bit with the following code.

        int n = 156;
    
    String bin = Integer.toBinaryString(n);
    System.out.println(bin);
    
    char arr[] = bin.toCharArray();
    for(int i = 0; i < arr.length; ++i) {
        System.out.println("Bit number " + (i + 1) + " = " + arr[i]);
    }
    

    10011100

    Bit number 1 = 1

    Bit number 2 = 0

    Bit number 3 = 0

    Bit number 4 = 1

    Bit number 5 = 1

    Bit number 6 = 1

    Bit number 7 = 0

    Bit number 8 = 0

提交回复
热议问题