简体   繁体   English

如何在保留长度的同时翻转 Java BitSet 中的所有位

[英]How to flip all the bits in Java BitSet while preserving its length

How can I flip all the bits in a Java BitSet , while preserving its length?如何翻转 Java BitSet中的所有位,同时保留其长度?

For example, given the following BitSet:例如,给定以下 BitSet:

BitSet.valueOf(new byte[] { 0b100111 })
// {0, 1, 2, 5}

Is there a simple method to flip all the bits, while preserving the BitSet length (6, in the above example)?是否有一种简单的方法来翻转所有位,同时保留 BitSet 长度(在上面的示例中为 6)?

I would like to get:我想得到:

BitSet.valueOf(new byte[] { 0b011000 })
// { 3, 4 }

BitSet has a flip(from, to) method , which allows you to flip bits in a range: BitSet有一个flip(from, to)方法,它允许您翻转某个范围内的位:

yourBitSet.flip(0, length);

The question you need to answer, however, is what you actually mean by "length".但是,您需要回答的问题是“长度”的实际含义。

  • A BitSet has the size() method, but that reports the number of bits it has allocated space for - perhaps more than you think the size is. BitSet具有size()方法,但它报告它已分配空间的位数 - 可能比您认为的大小更多。

  • It also has a length() method, which reports the highest-set bit in the bit set - perhaps less than you think the length of the bitset is.它还有一个length()方法,它报告位集中设置的最高位 - 可能小于您认为的位集长度。

Assuming you're OK with using length() , you can use:假设您可以使用length() ,您可以使用:

yourBitSet.flip(0, yourBitSet.length());

Of course, since this clears the highest-set bit, yourBitSet will have a smaller length() afterwards.当然,由于这会清除设置的最高位, yourBitSet之后的length()会更小。

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

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