Java中将字节转换为长度为4的布尔数组

发布于 2024-09-06 14:43:07 字数 43 浏览 1 评论 0原文

我需要在 Java 中将一个字节转换为 4 个布尔值的数组。我该怎么办?

I need to convert a byte into an array of 4 booleans in Java. How might I go about this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

芯好空 2024-09-13 14:43:07

根据 Michael Petrotta 对您问题的评论,您需要决定应该针对生成的布尔数组测试 8 位字节中的哪些位。出于演示目的,我们假设您需要最右边的四个位,那么类似这样的操作应该可以工作:

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;
}

此示例中的十六进制值(0x010x02 等)是特殊的位掩码在所需位置仅设置了一个位;因此 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:

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;
}

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.

留蓝 2024-09-13 14:43:07

关于规范

其他人提出了一个非常有效的观点:在Java中,Byte.SIZE == 8。也就是说,一个字节中有8位。您需要定义如何将 8 位映射为 4 个布尔值;否则我们只能猜测你想做什么。


BitSet 上,

无论您如何进行此映射,boolean[] 都不太可能真正是最佳表示。 java.util.BitSet 可能会更好。下面是一个示例:

import java.util.*;
public class BitSetExample {
    static BitSet toBitSet(byte b) {
        BitSet bs = new BitSet(Byte.SIZE);
        for (int i = 0; i < Byte.SIZE; i++) {
            if (((b >> i) & 1) == 1) {
                bs.set(i);
            }
        }
        return bs;
    }
    public static void main(String[] args) {
        BitSet bs = toBitSet((byte) 10);
        System.out.println(bs); // prints "{1, 3}"
        System.out.println(bs.get(3)); // prints "true"
        System.out.println(bs.get(2)); // prints "false"

        byte b = 25;
        System.out.println(toBitSet(b)); // prints "{0, 3, 4}"

        bs.or(toBitSet(b));
        System.out.println(bs); // prints "{0, 1, 3, 4}"
    }
}

上面的代码使用标准位探测技术将 byte 转换为 BitSet。请注意,(byte) 10 设置了其位 1 和 3(即 10 = 2^1 + 2^3,其中 ^ 表示求幂)。

该示例还展示了如何对 BitSet 执行or/set union 操作。


EnumSet

,另一个适用的数据结构可能是 EnumSet,这是一个 Set 实现针对 enum 进行了高度优化。下面是一个示例:

import java.util.*;
public class EnumSetExample {
    enum Style {
        BOLD, ITALIC, UNDERLINE, BLINKING;
    }
    public static void main(String[] args) {
        EnumSet<Style> myStyle = EnumSet.of(Style.BOLD, Style.UNDERLINE);

        System.out.println(myStyle);
        // prints "[BOLD, UNDERLINE]"

        System.out.println(myStyle.contains(Style.UNDERLINE));
        // prints "true"
        System.out.println(myStyle.contains(Style.BLINKING));
        // prints "false" (thank goodness!)

        myStyle.add(Style.ITALIC);
        System.out.println(myStyle);
        // prints "[BOLD, ITALIC, UNDERLINE]"
    }
}

另请参阅

  • 《Effective Java 第 2 版》第 32 项:使用 EnumSet 代替位字段

On specification

Others are raising a very valid point: in Java, Byte.SIZE == 8. That is, there are 8 bits in a byte. You need to define how you want to map 8 bits into 4 boolean 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. A java.util.BitSet may be better. Here's an example:

import java.util.*;
public class BitSetExample {
    static BitSet toBitSet(byte b) {
        BitSet bs = new BitSet(Byte.SIZE);
        for (int i = 0; i < Byte.SIZE; i++) {
            if (((b >> i) & 1) == 1) {
                bs.set(i);
            }
        }
        return bs;
    }
    public static void main(String[] args) {
        BitSet bs = toBitSet((byte) 10);
        System.out.println(bs); // prints "{1, 3}"
        System.out.println(bs.get(3)); // prints "true"
        System.out.println(bs.get(2)); // prints "false"

        byte b = 25;
        System.out.println(toBitSet(b)); // prints "{0, 3, 4}"

        bs.or(toBitSet(b));
        System.out.println(bs); // prints "{0, 1, 3, 4}"
    }
}

The above code uses the standard bit probing technique to convert a byte to a BitSet. 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 on BitSet.


On EnumSet

Possibly another applicable data structure is an EnumSet, which is a Set implementation highly optimized for enum. Here's an example:

import java.util.*;
public class EnumSetExample {
    enum Style {
        BOLD, ITALIC, UNDERLINE, BLINKING;
    }
    public static void main(String[] args) {
        EnumSet<Style> myStyle = EnumSet.of(Style.BOLD, Style.UNDERLINE);

        System.out.println(myStyle);
        // prints "[BOLD, UNDERLINE]"

        System.out.println(myStyle.contains(Style.UNDERLINE));
        // prints "true"
        System.out.println(myStyle.contains(Style.BLINKING));
        // prints "false" (thank goodness!)

        myStyle.add(Style.ITALIC);
        System.out.println(myStyle);
        // prints "[BOLD, ITALIC, UNDERLINE]"
    }
}

See also

  • Effective Java 2nd Edition, Item 32: Use EnumSet instead of bit fields
眼泪也成诗 2024-09-13 14:43:07

作为 maerics 答案的附录,如果需要,这就是如何将 bool 数组转换回字节的方法:

public static byte byteFromBooleanArray(bool[] _boolArray)
    {
        byte x = 0;
        x += _boolArray[0] ? (byte)1 : (byte)0;
        x += _boolArray[1] ? (byte)2 : (byte)0;
        x += _boolArray[2] ? (byte)4 : (byte)0;
        x += _boolArray[3] ? (byte)8 : (byte)0;

        return x;
    }

As an addendum to maerics' answer, this is how you could convert the bool array back into a byte, if needed :

public static byte byteFromBooleanArray(bool[] _boolArray)
    {
        byte x = 0;
        x += _boolArray[0] ? (byte)1 : (byte)0;
        x += _boolArray[1] ? (byte)2 : (byte)0;
        x += _boolArray[2] ? (byte)4 : (byte)0;
        x += _boolArray[3] ? (byte)8 : (byte)0;

        return x;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文