Java 简单的 boolean[] 到字节转换 [英] Java simple boolean[] to byte conversion
本文介绍了Java 简单的 boolean[] 到字节转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含 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.
这篇关于Java 简单的 boolean[] 到字节转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文