0

I wrote this function:

public static boolean[] convertByteArrayToBoolArray(byte[] byteArr) {

    int numberOfBits = (byteArr.length) * 8;

    boolean[] boolArr = new boolean[numberOfBits];

    int j =0;

    for(int i=0; i<byteArr.length; i++){

        Byte value = byteArr[i];

        boolArr[7+j] = ((value & 0x01) != 0);
        boolArr[6+j] = ((value & 0x02) != 0);
        boolArr[5+j] = ((value & 0x04) != 0);
        boolArr[4+j] = ((value & 0x08) != 0);
        boolArr[3+j] = ((value & 0x10) != 0);
        boolArr[2+j] = ((value & 0x20) != 0);
        boolArr[1+j] = ((value & 0x40) != 0);
        boolArr[0+j] = ((value & 0x80) != 0);

        j+= 8;
    }

    return boolArr;
}

how would i go about reversing this. A function which receives boolean[] and returns byte[]?

5
  • You might want to tag the language Commented Jan 16, 2015 at 18:31
  • Isn't a boolean just 1 byte? Commented Jan 16, 2015 at 19:21
  • A boolean is one bit, a byte is 8 bits. Commented Jan 16, 2015 at 19:25
  • I would write those 8 assignments in a loop as well, this is a lot of copy-paste code. Commented Jan 16, 2015 at 19:26
  • What have you tried? What part of the supplied code doesn't make sense to you? Also, why are you doing it? Commented Jan 16, 2015 at 19:45

1 Answer 1

1

You could try something like this:

private static byte boolsToByte(final boolean[] array, final int start) {
    byte b = 0;
    for (int i = 0; i < 8; i++) {
        if (array[start + i])
            b |= 1 << (7 - i);
    }
    return b;
}

public static byte[] convertBoolArrayToByteArray(boolean[] boolArr) {
    byte[] byteArr = new byte[boolArr.length/8];
    for (int i = 0; i < byteArr.length; i++)
        byteArr[i] = boolsToByte(boolArr, 8*i);
    return byteArr;
}
Sign up to request clarification or add additional context in comments.

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.