开发者

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';
    }     
    ret开发者_运维技巧urn 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...


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;
        }
    }

}


Doing a UnitTest to complete a similar task. Came up with the following:

BitSet bs = new BitSet(testArrayChar.length);

for (int y=0; y<testArrayChar.length; y++)
{
    if(testArrayChar[y]=='0')
    {
        bs.set(y, false);
    }
    else if(testArrayChar[y]=='1')
    {
        bs.set(y, true);
    }
}

Can add throwing exception if a character is something other than 0 or 1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜