trawww trawww - 5 months ago 23
Java Question

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

I am trying to write a TCP server/client program that transmits a stream of 4 bytes. Once the client receives the 4 bytes, I would then like to convert each received byte into a boolean[8]. Is there a way to do this? I can successfully transmit the 4 bytes from server to client, and the value of each byte received by the client matches the one transmitted to the server. I have pinpointed the error in the conversion method I wrote on the client side which is pasted below, I can post more code upon request if required.

SAMPLE 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;
}

Answer Source

You are specifying hexadecimal values with 0x, but then you go ahead and use the decimal numbers anyway. 0x08 happens to be 8, but 0x16 is not 16. Try

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