Java中将字节转换为长度为4的布尔数组
我需要在 Java 中将一个字节转换为 4 个布尔值的数组。我该怎么办?
I need to convert a byte into an array of 4 booleans in Java. How might I go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据 Michael Petrotta 对您问题的评论,您需要决定应该针对生成的布尔数组测试 8 位字节中的哪些位。出于演示目的,我们假设您需要最右边的四个位,那么类似这样的操作应该可以工作:
此示例中的十六进制值(
0x01
、0x02
等)是特殊的位掩码在所需位置仅设置了一个位;因此 0x01 仅设置了最右边的位,0x08 仅设置了右数第四位。通过使用按位 AND 运算符 (&
) 测试给定字节与这些值,如果该位已设置,您将得到该值,如果没有设置,则为零。如果您想检查除最右边的四个位之外的不同位,则必须创建不同的位掩码。Per Michael Petrotta's comment to your question, you need to decide which bits in the 8-bit byte should be tested for the resulting boolean array. For demonstration purposes, let's assume you want the four rightmost bits, then something like this should work:
The hexadecimal values (
0x01
,0x02
, etc.) in this example are special bit masks that have only a single bit set at the desired location; so 0x01 has only the rightmost bit set, 0x08 has only the fourth-from-right bit set. By testing the given byte against these values with the bitwise AND operator (&
) you will get that value back if the bit is set, or zero if not. If you want to check different bits, other than the rightmost four, then you'll have to create different bitmasks.关于规范
其他人提出了一个非常有效的观点:在Java中,
Byte.SIZE == 8
。也就是说,一个字节
中有8位。您需要定义如何将 8 位映射为 4 个布尔值;否则我们只能猜测你想做什么。在
BitSet
上,无论您如何进行此映射,
boolean[]
都不太可能真正是最佳表示。java.util.BitSet
可能会更好。下面是一个示例:上面的代码使用标准位探测技术将
byte
转换为BitSet
。请注意,(byte) 10
设置了其位 1 和 3(即10 = 2^1 + 2^3
,其中^
表示求幂)。该示例还展示了如何对
BitSet
执行or
/set union 操作。在
EnumSet
上,另一个适用的数据结构可能是
EnumSet
,这是一个Set
实现针对enum
进行了高度优化。下面是一个示例:另请参阅
EnumSet
代替位字段On specification
Others are raising a very valid point: in Java,
Byte.SIZE == 8
. That is, there are 8 bits in abyte
. You need to define how you want to map 8 bits into 4boolean
values; otherwise we can only guess what is it you're trying to do.On
BitSet
Regardless of how you do this mapping, however, it's unlikely that
boolean[]
really is the best representation. Ajava.util.BitSet
may be better. Here's an example:The above code uses the standard bit probing technique to convert a
byte
to aBitSet
. Note that a(byte) 10
has its bits 1 and 3 set (i.e.10 = 2^1 + 2^3
where^
denotes exponentiation).The example also shows how to perform an
or
/set union operation onBitSet
.On
EnumSet
Possibly another applicable data structure is an
EnumSet
, which is aSet
implementation highly optimized forenum
. Here's an example:See also
EnumSet
instead of bit fields作为 maerics 答案的附录,如果需要,这就是如何将 bool 数组转换回字节的方法:
As an addendum to maerics' answer, this is how you could convert the bool array back into a byte, if needed :