java 从 BitSet 转换为 Byte 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6197411/
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-10-30 14:46:42  来源:igfitidea点击:

Converting from BitSet to Byte array

javabitset

提问by JavaBits

I have picked up this example which converts BitSet to Byte array.

我选择了这个将 BitSet 转换为 Byte 数组的例子。

public static byte[] toByteArray(BitSet bits) {
    byte[] bytes = new byte[bits.length()/8+1];
    for (int i=0; i<bits.length(); i++) {
        if (bits.get(i)) {
            bytes[bytes.length-i/8-1] |= 1<<(i%8);
        }
    }
    return bytes;
}

But in the discussion forums I have seen that by this method we wont get all the bits as we will be loosing one bit per calculation. Is this true? Do we need to modify the above method?

但是在讨论论坛中,我看到通过这种方法我们不会获得所有位,因为每次计算都会丢失一位。这是真的?我们需要修改上面的方法吗?

回答by Jon Skeet

No, that's fine. The comment on the post was relating to the otherpiece of code in the post, converting from a byte array to a BitSet. I'd use rather more whitespace, admittedly.

不,没关系。帖子的评论与帖子中的一段代码有关,从字节数组转换为BitSet. 诚然,我会使用更多的空格。

Also this can end up with an array which is longer than it needs to be. The array creation expression could be:

此外,这最终可能会导致一个比它需要更长的数组。数组创建表达式可以是:

byte[] bytes = new byte[(bits.length() + 7) / 8];

This gives room for as many bits are required, but no more. Basically it's equivalent to "Divide by 8, but always round up."

这为需要的位提供了空间,但仅此而已。基本上它相当于“除以 8,但总是向上取整”。

回答by Lars Lynch

If you need the BitSet in reverse order due to endian issues, change:

如果由于字节序问题需要以相反的顺序设置 BitSet,请更改:

bytes[bytes.length-i/8-1] |= 1<<(i%8);

字节[bytes.length-i/8-1] |= 1<<(i%8);

to:

到:

bytes[i/8] |= 1<<(7-i%8);

字节[i/8] |= 1<<(7-i%8);

回答by Kamahire

This works fine for me. if you are using Java 1.7 then it has the method toByteArray().

这对我来说很好用。如果您使用的是 Java 1.7,那么它就有方法toByteArray()

回答by ryanbwork

FYI, using

仅供参考,使用

bits.length()

to fetch the size of the bitset may return incorrect results; I had to modify the original example to utilize the size() method to get the defined size of the bitset (whereas length() returns the number of bits set). See the thread below for more info.

获取位集的大小可能会返回不正确的结果;我不得不修改原始示例以利用 size() 方法来获取位集的定义大小(而 length() 返回设置的位数)。有关更多信息,请参阅下面的线程。

java.util.BitSet -- set() doesn't work as expected

java.util.BitSet -- set() 没有按预期工作