C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Set: This sets a bit to true (or 1). To set a bit to zero, please use the clear method or specify false in set.
Get: This returns a boolean indicating the value of the bit. True is 1 and false is 0.
Java program that creates, sets BitSet
import java.util.BitSet;
public class Program {
public static void main(String[] args) {
// Set two bits in a BitSet.
BitSet b = new BitSet();
b.set(10);
b.set(100);
// Get values of these bit positions.
boolean bit1 = b.get(5);
boolean bit2 = b.get(10);
boolean bit3 = b.get(100);
System.out.println(bit1);
System.out.println(bit2);
System.out.println(bit3);
}
}
Output
false
true
true
Java program that calls flip
import java.util.BitSet;
public class Program {
public static void main(String[] args) {
BitSet b = new BitSet();
// Set this bit.
b.set(3);
System.out.println(b.get(3));
// Flip the bit.
b.flip(3);
System.out.println(b.get(3));
}
}
Output
true
false
Java program that sets range
import java.util.BitSet;
public class Program {
public static void main(String[] args) {
BitSet b = new BitSet();
// Set bits in this range to true.
b.set(2, 5);
// Display first five bits.
for (int i = 0; i < 5; i++) {
System.out.println(b.get(i));
}
}
}
Output
false
false
true
true
true
Here: We set the first bit of the first byte to 1, so the first byte equals 1. The second byte, at position 8, also equals 1.
Java program that uses toByteArray
import java.util.BitSet;
public class Program {
public static void main(String[] args) {
BitSet b = new BitSet();
// Set bit 0 and bit 8 to true.
b.set(0);
b.set(8);
// Convert to byte array.
for (byte value : b.toByteArray()) {
System.out.println(value);
}
}
}
Output
1
1
Java program that gets range
import java.util.BitSet;
public class Program {
public static void main(String[] args) {
BitSet b = new BitSet();
b.set(3);
b.set(5);
// Get range of bits from original set.
BitSet b2 = b.get(3, 6);
// Display first five bits.
for (int i = 0; i < 5; i++) {
System.out.println(b2.get(i));
}
}
}
Output
true
false
true
false
false
No arguments: With no arguments, clear() will erase all bits in the BitSet. This is similar to creating an entirely new instance.
Java program that uses clear
import java.util.BitSet;
public class Program {
public static void main(String[] args) {
BitSet b = new BitSet();
// Set first four bits to true.
b.set(0, 4);
// Clear first two bits.
b.clear(0, 2);
// Display first four bits.
System.out.println(b.get(0));
System.out.println(b.get(1));
System.out.println(b.get(2));
System.out.println(b.get(3));
}
}
Output
false
false
true
true