3

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;
}
2
  • 2
    In future, it would be useful if you provided sample input, expected output and actual output. Commented Feb 19, 2014 at 22:33
  • @JonSkeet thank you for the tip, I will edit my question now and remember to supply this in the future. Commented Feb 19, 2014 at 22:45

2 Answers 2

7

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);
Sign up to request clarification or add additional context in comments.

Comments

2

Actually, there's a much beautiful way to do it.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.