vicky
vicky

Reputation: 67

Does BitSet in java stores bits or integers?

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?

Upvotes: 3

Views: 1434

Answers (2)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

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.)

Upvotes: 4

Minn
Minn

Reputation: 6124

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

Upvotes: 1

Related Questions