简体   繁体   English

BitSet 有时会丢弃 Bits

[英]BitSet sometimes drops Bits

I am currently trying to read a single bit from a File in Java.我目前正在尝试从 Java 中的文件中读取单个位。

I read the Data into a byte array and then convert the byte array into a Bitset.我将数据读入字节数组,然后将字节数组转换为位集。

The Problem is that sometimes there are a few bits missing in the converted Bitset.问题是有时在转换后的 Bitset 中缺少一些位。

In the following Example i have 2 Byte Arrays, each with 25 very similar Bytes.在下面的示例中,我有 2 个字节 Arrays,每个都有 25 个非常相似的字节。 But one is converted into the expected 200 bits and the other one into only 197 bits and i have no idea why.但是一个被转换成预期的 200 位,另一个被转换成只有 197 位,我不知道为什么。

import java.nio.ByteBuffer;
import java.util.BitSet;

public class Main {
    public static void main(String[] args) {
        ByteBuffer cb = ByteBuffer.wrap(new byte[] {(byte)0x18,(byte)0x8C,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,});
        BitSet cBits = BitSet.valueOf(cb);
        System.out.println(cBits.length());
        ByteBuffer db = ByteBuffer.wrap(new byte[] {(byte)0x17,(byte)0x8c,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x8c,(byte)0x8c,});
        BitSet dBits = BitSet.valueOf(db);
        System.out.println(dBits.length());
    }
}

Doodle涂鸦

The length() of a Java bitset is a consequence of the most significant set bit, not the length of the array which was passed. Java 位集的长度()是最高有效位的结果,而不是传递的数组的长度。 This is consistent with the bitset's description as a data structure which grows as needed--its logical size is a consequence of its set bits, not the physical capacity of some underlying buffer.这与将 bitset 描述为根据需要增长的数据结构是一致的——它的逻辑大小是其设置位的结果,而不是某些底层缓冲区的物理容量。

Returns the "logical size" of this BitSet: the index of the highest set bit in the BitSet plus one.返回此 BitSet 的“逻辑大小”:BitSet 中最高设置位的索引加一。 Returns zero if the BitSet contains no set bits.如果 BitSet 不包含设置位,则返回零。

Your first example has the most significant byte as 0x18, or binary 00011000. The three leading zero bits account for the discrepancy when compared with the second bitset, whose most significant byte is 0x8c (10001100)您的第一个示例的最高有效字节为 0x18,或二进制 00011000。与第二个位集(其最高有效字节为 0x8c(10001100))相比,三个前导零位解释了差异

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM