我写了这个函数:
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;
}
我将如何改变这一点。一个函数,它接收boolean []并返回byte []?
答案 0 :(得分:1)
您可以尝试这样的事情:
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;
}