Search code examples
javabitset

How to convert from char[] array to BitSet


I am using this program:

private static char[] toCharArray(final BitSet bs){    
    final int length = bs.length();     
    final char[] arr = new char[length];     
    for(int i = 0; i < length; i++){         
        arr[i] = bs.get(i) ? '1' : '0';
    }     
    return arr;
} 

to convert BitSet obj to char[] array. Now after doing some modification to the char[] (addition of some zero) array I want to convert it back to BitSet obj. Is there a way...


Solution

  • well no idea why you do this, but why not reverse your method?

    private static BitSet toBitset(final char[] entries){
            final int length = entries.length;
            BitSet bs = new BitSet(length);
            for(int i = 0; i < length; i++){
                    bs.set(i, entries[i] == '1');
            }
            return bs;
    }
    

    Edit: Since it seems you wanted to fix your method, there is only one way I could think of to force the char array to a specific size, but you need to know how many zeros you want to append to the end, so I rewrote your Method like this:

    private static char[] toCharArray(final BitSet bs, int expectedBits){
            if(expectedBits < bs.length()){
                expectedBits = bs.length();
            }
            final char[] arr = new char[expectedBits];
            for(int i = 0; i < expectedBits; i++){
                arr[i] = bs.get(i) ? '1' : '0';
            }
            return arr;
        }
    

    The Problem with using Bitmap is, it only stores "one"s, so the last entry in the BitSet will always be a "one", and the length will always refer to the last "one" in the BitSet.

    For Example:

     BitSet bs = new BitSet();
            for(int i = 0; i < 1000; i++){
                bs.set(i, false);
            }
     System.out.println(bs.length()); 
    

    Prints out "0" whereas

    BitSet bs = new BitSet();
    bs.set(10001, true); 
    System.out.println(bs.length()); 
    

    will print out 10002.

    This might help you (But you would need to edit the methods above accordingly):

    class FixedBitSet extends BitSet {
    
        private int maxLength = 0;
    
        public int maxLength(){
            return maxLength;
        }
    
        @Override
        public void set(int bitIndex, boolean value) {
            super.set(bitIndex, value);
            if(bitIndex > maxLength){
                maxLength = bitIndex;
            }
        }
    
    }