简体   繁体   中英

How to modify individual bits of a BitSet Class object

Example: I have a BitSet of 120 bits (010* 0 *001000......). Now I want to modify the 4th bit which is set to zero to 1.

SET(4,TRUE) - Something like this. Can it be done in Java?

I can do it through cov=nverting the bitset into Char[] array and then changing the exact bit and again reversing it back to Bitset but it use alot of unnecessary memory and will hamper performance. An example will be just fine. If more clarification is needed let me know through your comments.

The BitSet API is described in the javadoc , and there are a number of set(...) methods for setting or clearing individual bits, or ranges of bits.

BitSet b = ...
b.set(4, true);

Read the javadoc to find out if you are using the right value for the index. (Count from zero versus count from one.)

Actually, just read the javadoc.

Yes, we can actually do that. The BitSet class provide methods for setting and clearing individual Bits.

It has four set methods with different parameter inputs-

1.set(int bitIndex) -Sets the bit at the specified index to true.

2.set(int bitIndex, boolean value) -Sets the bit at the specified index to the specified value.

3.set(int fromIndex, int toIndex) -Sets the bits from the specified fromIndex (inclusive) to the specified toIndex (exclusive) to true.

4.set(int fromIndex, int toIndex, boolean value) -Sets the bits from the specified fromIndex (inclusive) to the specified toIndex (exclusive) to the specified value.

Ill try to include an example soon.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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