java 字节到“位”数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29396300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:11:36  来源:igfitidea点击:

Byte to "Bit"array

javabytebitprimitive

提问by user3394605

A byte is the smallest numeric datatype java offers but yesterday I came in contact with bytestreams for the first time and at the beginning of every package a marker byte is send which gives further instructions on how to handle the package. Every bit of the byte has a specific meaning so I am in need to entangle the byte into it's 8 bits.

字节是 java 提供的最小的数字数据类型,但昨天我第一次接触字节流,在每个包的开头都会发送一个标记字节,它提供了有关如何处理包的进一步说明。字节的每一位都有特定的含义,所以我需要将字节纠缠成 8 位。

You probably could convert the byte to a boolean array or create a switch for every case but that can't certainly be the best practice.

您可能可以将字节转换为布尔数组或为每种情况创建一个开关,但这肯定不是最佳实践。

How is this possible in java why are there no bit datatypes in java?

这在java中怎么可能为什么java中没有位数据类型?

回答by CodeCamper

Because there is no bit data type that exists on the physical computer. The smallest allotment you can allocate on most modern computers is a byte which is also known as an octet or 8 bits. When you display a single bit you are really just pulling that first bit out of the byte with arithmetic and adding it to a new byte which still is using an 8 byte space. If you want to put bit data inside of a byte you can but it will be stored as a at least a single byte no matter what programming language you use.

因为物理计算机上不存在位数据类型。您可以在大多数现代计算机上分配的最小分配是一个字节,也称为八位字节或 8 位。当您显示单个位时,您实际上只是使用算术将第一个位从字节中拉出,并将其添加到仍然使用 8 字节空间的新字节中。如果你想把位数据放在一个字节中,你可以,但无论你使用什么编程语言,它都会被存储为至少一个字节。

回答by jas

You could load the byte into a BitSet. This abstraction hides the gory details of manipulating single bits.

您可以将字节加载到 BitSet 中。这种抽象隐藏了操作单个位的血腥细节。

import java.util.BitSet;

public class Bits {
    public static void main(String[] args) {
        byte[] b = new byte[]{10};
        BitSet bitset = BitSet.valueOf(b);
        System.out.println("Length of bitset = " + bitset.length());
        for (int i=0; i<bitset.length(); ++i) {
            System.out.println("bit " + i + ": " + bitset.get(i));
        }
    }
}

$ java Bits
Length of bitset = 4
bit 0: false
bit 1: true
bit 2: false
bit 3: true

You can ask for any bit, but the length tells you that all the bits past length() - 1are set to 0(false):

您可以要求任何位,但长度告诉您过去的所有位length() - 1都设置为0(false):

System.out.println("bit 75: " + bitset.get(75));

bit 75: false

回答by muued

Have a look at java.util.BitSet. You might use it to interpret the byte read and can use the get method to check whether a specific bit is set like this:

看看 java.util.BitSet。您可以使用它来解释读取的字节,并可以使用 get 方法检查特定位是否设置如下:

byte b = stream.read();
final BitSet bitSet = BitSet.valueOf(new byte[]{b});
if (bitSet.get(2)) {
    state.activateComponentA();
} else {
    state.deactivateComponentA();
}
state.setFeatureBTo(bitSet.get(1));

On the other hand, you can create your own bitmask easily and convert it to a byte array (or just byte) afterwards:

另一方面,您可以轻松创建自己的位掩码,然后将其转换为字节数组(或仅字节):

final BitSet output = BitSet.valueOf(ByteBuffer.allocate(1));
output.set(3, state.isComponentXActivated());
if (state.isY){
    output.set(4);
}
final byte w = output.toByteArray()[0];

回答by Durandal

How is this possible in java why are there no bit datatypes in java?

How is this possible in java why are there no bit datatypes in java?

There are no bit data types in mostlanguages. And most CPU instruction sets have few (if any) instructions dedicated to adressing single bits. You can think of the lack of these as a trade-off between (language or CPU) complexity and need.

大多数语言都没有位数据类型。并且大多数 CPU 指令集几乎没有(如果有)专门用于处理单个位的指令。您可以将缺少这些视为(语言或 CPU)复杂性和需求之间的权衡。

Manipulating a singlebit can be though of as a special case of manipulating multiplebits; and languages as well as CPU's are equipped for the latter.

操作单个位可以看作是操作多个位的特例;为后者配备了语言和 CPU。

Very common operations like testing, setting, clearing, inverting as well as exclusive or are all supported on the integer primitive types (byte, short/char, int, long), operating on all bits of the type at once. By chosing the parameters appropiately you can select which bits to operate on.

非常常见的操作,如测试、设置、清除、反转以及互斥或在整数原始类型(字节、短/字符、整数、长)上都支持,一次对类型的所有位进行操作。通过适当地选择参数,您可以选择要操作的位。

If you think about it, a byte array isa bit array where the bits are grouped in packages of 8. Adressing a single bit in the array is relatively simple using logical operators (AND &, OR |, XOR ^and NOT ~).

仔细想想,字节数组一个位数组,其中的位以 8个一组进行分组。使用逻辑运算符(AND &、OR |、XOR^和 NOT ~)处理数组中的单个位相对简单。

For example, testing if bit N is set in a byte can be done using a logical AND with a mask where only the bit to be tested is set:

例如,测试是否在一个字节中设置了位 N 可以使用带有掩码的逻辑 AND 来完成,其中仅设置了要测试的位:

public boolean testBit(byte b, int n) {
    int mask = 1 << n; // equivalent of 2 to the nth power
    return (b & mask) != 0;
}

Extending this to a byte array is no magic either, each byte consists of 8 bits, so the byte index is simply the bit number divided by 8, and the bit number inside that byte is the remainder (modulo 8):

将其扩展到字节数组也不是魔术,每个字节由 8 位组成,因此字节索引只是位号除以 8,该字节内的位号是余数(模 8):

public boolean testBit(byte[] array, int n) {
    int index = n >>> 3; // divide by 8
    int mask = 1 << (n & 7); // n modulo 8
    return (array[index] & mask) != 0;
}