如何将布尔数组转换为字节数组
How to convert boolean array to byte array
我写了这个函数:
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[] 和 returns byte[]?
的函数
您可以尝试这样的操作:
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;
}
我写了这个函数:
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[] 和 returns byte[]?
的函数您可以尝试这样的操作:
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;
}