Java 简单的布尔值[] 到字节的转换
Java simple boolean[] to byte conversion
我有一个包含 8 个布尔值的数组,我想将其简单地转换为一个字节。有没有简单的方法可以做到这一点?还是我必须使用 for 循环?
就我个人而言,我更喜欢简单的最多两行的解决方案(如果存在的话)。
感谢您的帮助。
编辑:可能的重复只是一个字节的一个布尔值,我有一个数组。
另一个编辑:我从 udp 数据包中获取一个字节,然后将第一位(布尔值)设置为 false,然后我需要再次从中获取一个字节。
我认为一个循环更好,但如果你必须有一个衬里:
byte b = (byte)((bool[0]?1<<7:0) + (bool[1]?1<<6:0) + (bool[2]?1<<5:0) +
(bool[3]?1<<4:0) + (bool[4]?1<<3:0) + (bool[5]?1<<2:0) +
(bool[6]?1<<1:0) + (bool[7]?1:0));
对于输入:
boolean[] bool = new boolean[] {false,false,true,false,true,false,true,false};
你得到了字节 42。
如果我理解你的问题是正确的,那么你想将由它的位模式表示的字节转换为布尔数组......
如果是这样,那么这是一个解决方案:
public static void main(String[] args) {
// The integer where the result will be build up
int result = 0;
// The bit-pattern as an array of booleans
// 2^0 Position is at bools[0] !!
// so this is the byte '0 1 0 1 0 1 0 1' --> decimal : 85
boolean[] bools = new boolean[]{ true, false, true, false, true, false, true, false };
// iterate through the 'bits'
// and set the corresponding position in the result to '1' if the 'bit' is set
for (int i = 0; i < bools.length; i++) {
if (bools[i]) {
result |= 1 << i;
}
}
System.out.println(result); // Prints '85'
}
我会这样做:
byte b = 0;
for(int i=0;i<8;i++) if(binaryValues[i]) b |= (128 >> i);
return b;
我有一个包含 8 个布尔值的数组,我想将其简单地转换为一个字节。有没有简单的方法可以做到这一点?还是我必须使用 for 循环?
就我个人而言,我更喜欢简单的最多两行的解决方案(如果存在的话)。
感谢您的帮助。
编辑:可能的重复只是一个字节的一个布尔值,我有一个数组。
另一个编辑:我从 udp 数据包中获取一个字节,然后将第一位(布尔值)设置为 false,然后我需要再次从中获取一个字节。
我认为一个循环更好,但如果你必须有一个衬里:
byte b = (byte)((bool[0]?1<<7:0) + (bool[1]?1<<6:0) + (bool[2]?1<<5:0) +
(bool[3]?1<<4:0) + (bool[4]?1<<3:0) + (bool[5]?1<<2:0) +
(bool[6]?1<<1:0) + (bool[7]?1:0));
对于输入:
boolean[] bool = new boolean[] {false,false,true,false,true,false,true,false};
你得到了字节 42。
如果我理解你的问题是正确的,那么你想将由它的位模式表示的字节转换为布尔数组...... 如果是这样,那么这是一个解决方案:
public static void main(String[] args) {
// The integer where the result will be build up
int result = 0;
// The bit-pattern as an array of booleans
// 2^0 Position is at bools[0] !!
// so this is the byte '0 1 0 1 0 1 0 1' --> decimal : 85
boolean[] bools = new boolean[]{ true, false, true, false, true, false, true, false };
// iterate through the 'bits'
// and set the corresponding position in the result to '1' if the 'bit' is set
for (int i = 0; i < bools.length; i++) {
if (bools[i]) {
result |= 1 << i;
}
}
System.out.println(result); // Prints '85'
}
我会这样做:
byte b = 0;
for(int i=0;i<8;i++) if(binaryValues[i]) b |= (128 >> i);
return b;