I am sending byte[]
arrays over a socket connection in Java.
I have a pretty long boolean[]
array, where array.length % 8 == 0
.
I'd like to convert this boolean[]
array into a byte[]
array with 8 times as few elements, so that I can then send the byte[]
over the socket connection.
The boolean[]
array looks like this: 01011010 10101010 01100011 11001010
etc.
The byte[]
in this case should look like this: 0x5A 0xAA 0x63 0xCA
.
I have found some code on another question on how to convert a single byte
into a boolean[]
array and added a new method to it to convert an entire array here:
public static boolean[] booleanArrayFromByteArray(byte[] x) {
boolean[] y = new boolean[x.length * 8];
int position = 0;
for(byte z : x) {
boolean[] temp = booleanArrayFromByte(z);
System.arraycopy(temp, 0, y, position, 8);
position += 8;
}
return y;
}
public static boolean[] booleanArrayFromByte(byte x) {
boolean bs[] = new boolean[4];
bs[0] = ((x & 0x01) != 0);
bs[1] = ((x & 0x02) != 0);
bs[2] = ((x & 0x04) != 0);
bs[3] = ((x & 0x08) != 0);
return bs;
}
I'd like to know if there is a more efficient way of doing this.
Edit: Thanks