Java 简单的 boolean[] 到字节转换

2022-01-19 00:00:00 arrays byte boolean java primitive-types

我有一个包含 8 个布尔值的数组,我想简单地将其转换为一个字节.有没有一种简单的方法可以做到这一点?还是我必须使用 for 循环?

I have an array of 8 booleans which I want to simply convert to a byte. Is there a simple way to do this? Or do I have to use for loop?

如果存在,我个人更喜欢最多两行的简单解决方案.

Personally I'd prefer a simple up to two lines solution if it exists.

感谢您的帮助.

可能的重复只是一个字节的布尔值,我有一个数组.

Possible duplicate is just one boolean to a byte, I have an array.

另一个我从 udp 数据包中获取一个字节,然后将第一位(布尔值)设置为 false,然后我需要再次从中获取一个字节.

ANOTHER I get a byte from a udp packet then I set the first bit (boolean) to false, then I would need to get a byte out of that again.

推荐答案

我认为循环更好,但如果你必须有一个单行:

I think a loop is better, but if you must have a one liner :

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.

相关文章