Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does BitSet in java stores bits or integers?

Tags:

java

bitset

I came across many coding sites about bitset. But i cant understand whether it stores bits or integers.

BitSet creates an array of bits represented by boolean values.

import java.util.*; 
public class GFG 
{ 
    public static void main(String[] args) 
    { 
       BitSet bs1 = new BitSet(); 
       BitSet bs2 = new BitSet(6); 

       bs1.set(0); 
       bs1.set(1); 
       bs1.set(2); 
       bs1.set(4); 

       bs2.set(4); 
       bs2.set(6); 
       bs2.set(5); 
       bs2.set(1); 
       bs2.set(2); 
       bs2.set(3); 

       System.out.println("bs1  : " + bs1); 
       System.out.println("bs2  : " + bs2); 
    } 
} 
Output:

bs1 : {0, 1, 2, 4}
bs2 : {1, 2, 3, 4, 5, 6}

BitSet stores bits or integers?

How does it stores that in memory?

How the values change when any manipulation is done?

like image 935
vicky Avatar asked Aug 30 '26 11:08

vicky


2 Answers

Typically BitSet would be implemented using a long[]. Each long stores 64 consecutive possible bit positions. The array needs a size equal to the highest set bit index minus one (to allow for index 0), divided by 64 (rounded down). Set bits are represented as a binary 1 and bits present in the array but not set as a binary 0.

So the internal representation of your examples would be something like:

bs1 = new long[] { 0b00010111L }; // 23
bs2 = new long[] { 0b01111110L }; // 126
     // bit indexes: 76543210

(Bits 8-63 elided from constants - add all the zeros if your want.)

like image 97
Tom Hawtin - tackline Avatar answered Sep 03 '26 06:09

Tom Hawtin - tackline


The BitSet stores bits using an array of longs:

private long[] bits;

Manipulating this means you manipulate bits of those longs using bitwise operations and shifts

public void set(int pos)
{
  int offset = pos >> 6; // divide by 2^6 = 64
  ensure(offset);        // if needed extend array
  // ArrayIndexOutOfBoundsException subclasses IndexOutOfBoundsException,
  // so we'll just let that be our exception.
  bits[offset] |= 1L << pos; // set bit using OR and a shift
}

Some illustration of whats going on for 6 bits (index 0-5):

init  000000

set 3:
      000000
   OR 001000 = 1 << 3
   =  001000

set 5:
      001000
   OR 100000 = 1 << 5
   =  101000

This means you take all bits of the current bitmask and the newly set bit of the desired offset to calculate the new bitmask.

Source Code

like image 21
Minn Avatar answered Sep 03 '26 04:09

Minn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!