Convert bitset to int array and string : BitSet « Collections Data Structure « Java






Convert bitset to int array and string

  
import java.util.BitSet;

public class Main {
  public static void main(String[] args) {
    BitSet bs = new BitSet();
    bs.set(31);
    bs.set(15);
    bs.set(18);
    int[] intArray = bits2Ints(bs);

    for (int i = 0; i < intArray.length; i++)
      System.out.println(toBinary(intArray[i]));
  }

  static int[] bits2Ints(BitSet bs) {
    int[] temp = new int[bs.size() / 32];

    for (int i = 0; i < temp.length; i++)
      for (int j = 0; j < 32; j++)
        if (bs.get(i * 32 + j))
          temp[i] |= 1 << j;

    return temp;
  }

  static String toBinary(int num) {
    StringBuffer sb = new StringBuffer();

    for (int i = 0; i < 32; i++) {
      sb.append(((num & 1) == 1) ? '1' : '0');
      num >>= 1;
    }

    return sb.reverse().toString();
  }

}

   
    
  








Related examples in the same category

1.Java 1.5 (5.0) Changes to the API: several of the new bit manipulation methods in Integer.Java 1.5 (5.0) Changes to the API: several of the new bit manipulation methods in Integer.
2.The use of BitSetThe use of BitSet
3.Manipulating the BitSetManipulating the BitSet
4.Another Bitset demoAnother Bitset demo
5.Operations on series of numbers
6.BitOHoney
7.BitOps
8.Implementation of a bit map of any size, together with static methods to manipulate int, byte and byte[] values as bit maps
9.Operations on bit-mapped fields.