Is there a way to convert a byte to a logical array in java?

I am trying to write a TCP server / client program that transmits a stream of 4 bytes. As soon as the client receives 4 bytes, I would like to convert each received byte to logical [8]. Is there any way to do this? I can successfully transfer 4 bytes from server to client, and the value of each byte received by the client corresponds to the one that was transferred to the server. I pointed out an error in the conversion method that I wrote on the client side, which is inserted below, I can send more code on request, if necessary.

SIGNAL INPUT ====== (- 2 11111110) (-10 11110110) (-2 11111110) (-2 11111110)

ACTUAL OUTPUT ==== (- 2 11111110) (-10 11110110) (-2 11111110) (-2 11111110)

EXPECTED OUTPUT == (- 2 11111110) (-10 11110110) (-2 11111110) (-2 11111110) [Same as input]

public static boolean[] byteToBoolArr(byte x) {
    boolean[] boolArr = new boolean[8];
    boolArr[0] = ((x & 0x01) != 0);
    boolArr[1] = ((x & 0x02) != 0);
    boolArr[2] = ((x & 0x04) != 0);
    boolArr[3] = ((x & 0x08) != 0);

    boolArr[4] = ((x & 0x16) != 0);
    boolArr[5] = ((x & 0x32) != 0);
    boolArr[6] = ((x & 0x64) != 0);
    boolArr[7] = ((x & 0x128) != 0);
    return boolArr;
}
+3
source share
2 answers

You specify hexadecimal values ​​with 0x, but then you continue to use decimal numbers. 0x08It turns out 8, but 0x16not 16. Try

boolArr[4] = ((x & 0x10) != 0);
boolArr[5] = ((x & 0x20) != 0);
boolArr[6] = ((x & 0x40) != 0);
boolArr[7] = ((x & 0x80) != 0);
+5
source

Actually, there is a very beautiful way to do this.

public static boolean[] byteToBoolArr(byte b) {
    boolean boolArr[] = new boolean[8];
    for(int i=0;i<8;i++) boolArr[i] = (b & (byte)(128 / Math.pow(2, i))) != 0;
    return boolArr;
}
+1
source

All Articles