Monday, 14 May 2012

Bitset to String and vice versa

A Bit Set - Nothing to do
with the Java class...
BitSet ("a vector of bits that grows as needed") can easily be serialized into String. In case one needs to convert the serialized String back to a BitSet object, here's a snippet:

Here is the code:
 public class BitSetParser {  
   private final String string;  
   private int size = 1024;  
   public BitSetParser(final String string) {  
     this.string = string;  
   }  
   public void setSize(int size) {  
     this.size = size;  
   }  
   public BitSet parse() {  
     BitSet bs = new BitSet(size);  
     String[] tokens = string.replaceAll("\\{", "").replaceAll("}", "").split(",");  
     int i;  
     if (tokens.length > 0) {  
       for (String s : tokens) {  
         s = s.trim();  
         if (!s.isEmpty()) {  
           i = Integer.parseInt(s);  
           bs.set(i);  
         } else {  
           break;  
         }  
       }  
     }  
     return bs;  
   }  
 }  

3 comments:

  1. I needed that one :) Thanks!

    ReplyDelete
  2. Hello! Shouldn't the code set a bit on its position? Otherwise, if you have the following bits: 1,0,1 you'd get bit set with only 0-th position, but not the 2-nd position.

    Perhaps, you have some other use case here.

    ReplyDelete
    Replies
    1. Yes, what I'm trying to do here is to just map `String` objects to `BitSet` ones. The post is quite old (and not so well documented), so I don't remember the exact use case now.

      Delete