Java boolean []到byte []并返回 [英] Java boolean[] to byte[] and back
问题描述
我正在通过Java中的套接字连接发送byte[]
数组.
I am sending byte[]
arrays over a socket connection in Java.
我有一个很长的boolean[]
数组,其中array.length % 8 == 0
.
I have a pretty long boolean[]
array, where array.length % 8 == 0
.
我想将此boolean[]
数组转换为元素数量减少8倍的byte[]
数组,以便随后可以通过套接字连接发送byte[]
.
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.
boolean[]
数组如下所示:01011010 10101010 01100011 11001010
等.
在这种情况下,byte[]
应该看起来像这样:0x5A 0xAA 0x63 0xCA
.
The byte[]
in this case should look like this: 0x5A 0xAA 0x63 0xCA
.
我在另一个问题上找到了一些有关如何将单个byte
转换为boolean[]
数组的代码,并在此处添加了新方法以转换整个数组:
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.
谢谢
推荐答案
您可以这样做.
public byte[] toBytes(boolean[] input) {
byte[] toReturn = new byte[input.length / 8];
for (int entry = 0; entry < toReturn.length; entry++) {
for (int bit = 0; bit < 8; bit++) {
if (input[entry * 8 + bit]) {
toReturn[entry] |= (128 >> bit);
}
}
}
return toReturn;
}
这依赖于toReturn
将被全零初始化的事实.然后针对在input
中遇到的每个true
,在toReturn
的相应条目内设置相应的位.
This relies on the fact that toReturn
will be initialised with all zeroes. Then for each true
that we encounter in input
, we set the appropriate bit within the appropriate entry in toReturn
.
这篇关于Java boolean []到byte []并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!